Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Method 1: Using STACK
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null)
{
return head;
}
Stack<ListNode> st = new Stack<ListNode>();
var tempHead = head;
while(tempHead.next != null)
{
st.Push(tempHead);
tempHead = tempHead.next;
}
head = tempHead;
while(st.Count > 0)
{
tempHead.next = st.Pop();
tempHead = tempHead.next;
}
tempHead.next = null;
return head;
}
}
Method 2: Using Previous, Next and Current Pointers
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null)
{
return head;
}
ListNode cNode = head, nNode = head, pNode = null;
while(cNode != null)
{
nNode = cNode.next;
cNode.next = pNode;
pNode = cNode;
cNode = nNode;
}
return pNode;
}
}
Method 3 – Using a new list (Not using extra space just swapping references of Nodes)
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return head;
ListNode tempHead = null;
ListNode temp = head;
while(temp != null)
{
var temp1 = temp.next;
temp.next = tempHead;
tempHead = temp;
temp = temp1;
}
return tempHead;
}
}