定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
一直没理解了递归解法,今天重新做时,豁然开朗,记录一下,好记性不如烂笔头(烂键盘)!
emmmmm常规解法:
把head拿到记为cur,断开与下一个的链接,断开之前用temp记下来下一个节点。
把pre指向cur,cur指向temp,循环到尾结束,返回pre。
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}
ListNode cur= head,pre=null,temp=null;
while(cur!=null){
temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}
}
然后递归解法:
- 走到最后一个节点
- 回指,最骚的一步:head.next.next=head;
- 断开之前连接
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode cur=reverseList(head.next);
head.next.next=head;
head.next=null;
return cur;
}
}