Reverse a singly linked list.
Click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
iteratively:
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten PublicListNode reverselist (ListNode head) { OneListNode first =NULL; AListNode second =head; - while(Second! =NULL){ -ListNode tmp =Second.next; theSecond.next =First ; -First =second; -Second =tmp; - } + returnFirst ; - } +}
Recursively:
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten PublicListNode reverselist (ListNode head) { One if(Head = =NULL|| Head.next = =NULL)returnhead; AListNode NextNode =Head.next; -Head.next =NULL; -ListNode Newhead =reverselist (nextnode); theNextnode.next =head; - returnNewhead; - } -}
Reverse Linked List