Reverse a singly linked list.
Recursive method
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {public ListNode reverselist (ListNode head) { return reverselist (null, head); } Private ListNode reverselist (ListNode left,listnode right) { if (right==null) return to left; ListNode rnext = Right.next; Right.next = left; Return Reverselist (Right,rnext);} }
Iterative methods
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {public ListNode reverselist (ListNode head) { if (head==null) return head; ListNode lefthead = null; ListNode current = head; ListNode nxt = Head.next; while (current!=null) { current.next = Lefthead; Lefthead = current; current = NXT; if (current==null) break; NXT = Nxt.next; } return lefthead;} }
Reverse Linked List