链表

难度简单

题目描述

image.png

解题思路

利用两个指针,pre指向前一个节点,cur指向当前节点,就地反转

Code

  1. class ListNode {
  2. int val;
  3. ListNode next;
  4. ListNode() {
  5. }
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. ListNode(int val, ListNode next) {
  10. this.val = val;
  11. this.next = next;
  12. }
  13. }
  14. public ListNode reverseList(ListNode head) {
  15. ListNode pre = null, cur = head;
  16. while (cur != null) {
  17. ListNode temp = cur.next;
  18. cur.next = pre;
  19. pre = cur;
  20. cur = temp;
  21. }
  22. return pre;
  23. }