Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Java code:iteratively:
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode reverselist (ListNode head) {if(Head = =NULL|| Head.next = =NULL) { returnHead; } listnode p1=Head; ListNode P2=Head.next; Head.next=NULL; while(P1! =NULL&& P2! =NULL) {ListNode P3=P2.next; P2.next=P1; P1=P2; if(p3!=NULL) {P2=P3; }Else { Break; } } returnP2; }}
Recursively:
Version One:
PublicListNode reverselist (ListNode head) {if(head==NULL|| Head.next = =NULL) returnHead; //Get second nodeListNode second =Head.next; //set first ' next ' is nullHead.next =NULL; ListNode Rest=Reverselist (second); Second.next=Head; returnrest; }
Version two:
Public ListNode reverselist (ListNode head) { returnnull); } Public ListNode Reverselistint (ListNode head, ListNode newhead) { ifnull) return newhead; = Head.next; = Newhead; return Reverselistint (Next, head); }
20160601:
Iteration:
Public classSolution { PublicListNode reverselist (ListNode head) {//Iteration//Base Case if(Head = =NULL|| Head.next = =NULL) { returnHead; } ListNode Pre=NULL; ListNode cur=Head; ListNode Next=NULL; while(cur! =NULL) {Next=Cur.next; Cur.next=Pre; Pre=cur; Cur=Next; } returnPre; }}
Recursion:
Public classSolution { PublicListNode reverselist (ListNode head) {//recursion//Base Case if(Head = =NULL|| Head.next = =NULL) { returnHead; } ListNode NextNode=Head.next; ListNode Newhead=reverselist (NextNode); Nextnode.next=Head; Head.next=NULL; returnNewhead; }}
Reference:
1. http://www.programcreek.com/2014/05/leetcode-reverse-linked-list-java/
2. Https://leetcode.com/discuss/34474/in-place-iterative-and-recursive-java-solution
Leetcode Reverse Linked List