Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

206. Reverse Linked List #11

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

有链表1-》2-》3 p1成为2-》3,头后面成了空,就成为最后一个节点 p2成为了1 head成为了2-》3 进入下次循环,p1成为3,head.next=p2意味着把上一次的p2=1接在3之后。如此循环完成反转 public class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode p1 = null; ListNode p2 = null; while(head != null) { p1 = head.next; head.next = p2; p2 = head; head = p1; } return p2; } }

discuss有递归的方法还不错 ets take 1->2->3->4 as an example, hope this can help you to get basic understanding of how to use recursive method.

public class Solution { public ListNode reverseList(ListNode head) { if(head ==null||head.next == null) return head; //here is the base case

ListNode second = head.next; //here "second" means "2->3->4", aka. the rest part

ListNode rest = reverseList(second); //here, we use recursive method to take care of the rest part, if you think it's hard to understand, just ignore all those steps and tell yourself, recursive will take care of this and help me to change "2->3->4" to "4->3->2", so here , "rest" is the head "4" of this linked list that we just got, now all we need to do is to make sure 2.next is 1, and 1->next = null;

second.next = head; // here we make sure 2.next = 1, recall that the pointer "second" is still point to "2", and pointer 'head' points to '1';so we get '4->3->2<=>1' since head.next(1.next) still points to second(2), lets get rid of this now

head.next = null; // here we get rid of the "1->2", now what left is "4->3->2->1" which is what we need;

return rest; // as i said, 'rest' points to '4' aka the head of '4->3->2->1', here we return rest aka the result linked list } }