Skip to content

Commit

Permalink
Create RevLinkedList.java
Browse files Browse the repository at this point in the history
rev linked list
  • Loading branch information
damonw-bds authored Mar 4, 2024
1 parent 2875cbe commit 7d46a9f
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions RevLinkedList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
class Node {
int data;
Node next;

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

class LinkedList {
Node head;

public void reverse() {
Node prev = null;
Node current = head;
Node next = null;

while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}

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

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("Original linked list:");
list.printList();
list.reverse();
System.out.println("Reversed linked list:");
list.printList();
}
}

0 comments on commit 7d46a9f

Please sign in to comment.