Iteration:
Code:
/**
* Definition for singly-linked list.
* Public class ListNode {
* int val;
* ListNode Next;
* ListNode (int x) {val = x;}
* }
*/
public class Solution {
Public ListNode reverselist (ListNode head) {
if (head = = NULL) return null;
ListNode tail = head.next;
ListNode cur = head;
while (tail!= null) {
ListNode NEX = Tail.next;
Tail.next = head;
Cur.next = NEX;
head = tail;
tail = NEX;
}
return head;
}
}
Recursion:
Code:
/**
* Definition for singly-linked list.
* Public class ListNode {
* int val;
* ListNode Next;
* ListNode (int x) {val = x;}
* }
*/
public 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;
}
}
Jan 10-reverse Linked list;data Structure; Linked List; Pointer; Iteration & Recursion