Pages

Tuesday, 20 June 2023

Reverse a LinkedList

Input: Head of following linked list 
1->2->3->4->NULL 
Output: Linked list should be changed to, 
4->3->2->1->NULL

Input: Head of following linked list 
1->2->3->4->5->NULL 
Output: Linked list should be changed to, 

5->4->3->2->1->NULL

Code:[Java]

package com.learning.learn.linkedlist;

public class LinkedList {

static Node head;

static class Node {
int data;
Node next;
Node(int d) {
this.data = d;
next = null;
}
}

Node reverse(Node node) {
Node prev = null;
Node curr = node;
Node next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
node = prev;
return node;
}

void printList(Node node) {
while(node != null) {
System.out.print(node.data+" ");
node = node.next;
}
}

public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);

System.out.println("Given :");
list.printList(head);
head = list.reverse(head);
System.out.println();
System.out.println("Reversed :");
list.printList(head);
}

}

 

No comments:

Post a Comment

Code Review

 SOLID Principles S – Single Responsibility Principle There should never be more than one reason for a class to change. O – Open-Closed Prin...