反转链表需要三个节点哦
反转链表需要三个节点哦
反转链表需要三个节点哦
已反转的链表头节点 ret 1 👈 2 👈 3 👈 ④
未反转的链表头节点 head ⑤ 👉 6 👉 7 👉 8 👉 9
**第一步:**首先需要一个临时节点 tmp 指向 ⑤ 然后 head节点后移 ⑥👉 7 👉 8 👉 9
**第二步:**这时 tmp 节点指向 ret tmp.next = ret;
链表变为 1 👈 2 👈 3 👈 ④ 👈 5
**第三步:**ret 指向 tmp 节点 链表变为 1 👈 2 👈 3 👈 4 👈 ⑤
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return head;
}
ListNode tmp = head;
ListNode ret = null;
while(head!=null){
tmp = head;
head = head.next;
tmp.next = ret;
ret = tmp;
}
return ret;
}
}