剑指Offer第十五题:反转链表
输入一个链表,反转链表后,输出新链表的表头。
头插法
-
初始化:
头结点pre = new ListNode(head);
临时结点next,指向head的下一个结点 -
遍历链表,循环停止条件next == null
2.1 先让head指向next结点 head = next
2.2 先用临时结点存储下一个结点next = next.next
2.3 进行反转,修改head.next,让head指向pre: head.next = pre;
2.4 更新pre的位置 pre = head -
return pre
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
//使用头插法
if(head == null){
return head;
}
ListNode next = head.next;
ListNode pre = new ListNode( head.val );
while(next != null){
head = next;
next = next.next;
head.next = pre;
pre = head;
}
return pre;
}
}
递归
例如A->B->C
当递归到C时return C,此时head是B B的next是C
所以B的next的next head.next.next = head 相当于C->B
再让head.next = null 相当于 C->B->null
返回 return C 相当于 C->B->null
此时倒数第二层递归中 head是A A的next是B
A的next的next head.next.next = head 相当于 B->A
再让 head.next = null B->A->null
返回 return C 相当于 C->B->A-null
//递归
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode temp = ReverseList(head.next);
head.next.next = head;
head.next = null;
return temp;
}