力扣:206. 反转链表
反转链表,用迭代法进行操作,核心点是用一个临时变量存储交换,代码:
public ListNode reverseList2(ListNode head) {if (head == null || head.next == null) {return head;}ListNode r = null;while (head != null) {// 临时变量ListNode t = r;r = head;head = head.next;r.next = t;}return r;}
递归有点绕,涉及到引用问题,先看代码:
public ListNode reverseList(ListNode head) {if(head.next == null){return head;}ListNode tailNode = reverseList(head.next);// 反正赋值head.next.next = head;// 清除回环head.next = null;return tailNode;}
这里假设我们head传入的值是这样的:
5 -> 4 -> 3 -> 2 -> 1
那么:
- 写递归先找到递归退出条件,第2行中,如果链表到尾部了,就退出,此时返回的head是 1;
- 第6行中,递归返回一个 tailNode 节点,其实它是尾部节点,此时 tailNode=1, head = 2 -> 1;
- 第8行中的head是倒数第二个节点,将它赋值给链表尾部,此时形成一个环形链表 head = 2 -> 1 -> 2 -> 1 …,tailNode = 1 -> 2 -> 1 -> 2 …
- 第9行中将head.next = null,此时链表变为 head = 2,因为 head = 2 tailNode中要保留最小的一部分,所以 tailNode = 1 -> 2
- 重复该步骤
