Here is the code implementation in java of a LinkedList and then the method to reverse it.
package com.developerasks.dailycodingpeoblems;
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
}
public class LinkedListFor73 {
Node head;
int size = 0;
public LinkedListFor73 Insert(int val, LinkedListFor73 list) {
// TODO Auto-generated constructor s
Node node = new Node(val);
node.next = null;
if (list.head == null) {
list.head = node;
size++;
}
else {
Node last = list.head;
while (last.next != null) {
last = last.next;
}
last.next = node;
size++;
}
return list;
}
public void print(LinkedListFor73 list) {
Node curr = list.head;
while (curr != null) {
System.out.print(curr.val + " ");
// Go to next node
curr = curr.next;
}
System.out.println("done\n");
}
public void reverseLinkedList(LinkedListFor73 linkedList) {
Node previous = null;
Node current = linkedList.head;
Node next;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
linkedList.head = previous;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedListFor73 hj = new LinkedListFor73();
hj.Insert(2, hj);
hj.Insert(3, hj);
hj.Insert(4, hj);
hj.Insert(5, hj);
hj.Insert(6, hj);
hj.Insert(7, hj);
hj.Insert(8, hj);
hj.print(hj);
System.out.println("head is " + hj.head.val);
hj.reverseLinkedList(hj);
hj.print(hj);
System.out.println("head is " + hj.head.val);
}
}
package com.developerasks.dailycodingpeoblems;
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
}
public class LinkedListFor73 {
Node head;
int size = 0;
public LinkedListFor73 Insert(int val, LinkedListFor73 list) {
// TODO Auto-generated constructor s
Node node = new Node(val);
node.next = null;
if (list.head == null) {
list.head = node;
size++;
}
else {
Node last = list.head;
while (last.next != null) {
last = last.next;
}
last.next = node;
size++;
}
return list;
}
public void print(LinkedListFor73 list) {
Node curr = list.head;
while (curr != null) {
System.out.print(curr.val + " ");
// Go to next node
curr = curr.next;
}
System.out.println("done\n");
}
public void reverseLinkedList(LinkedListFor73 linkedList) {
Node previous = null;
Node current = linkedList.head;
Node next;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
linkedList.head = previous;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedListFor73 hj = new LinkedListFor73();
hj.Insert(2, hj);
hj.Insert(3, hj);
hj.Insert(4, hj);
hj.Insert(5, hj);
hj.Insert(6, hj);
hj.Insert(7, hj);
hj.Insert(8, hj);
hj.print(hj);
System.out.println("head is " + hj.head.val);
hj.reverseLinkedList(hj);
hj.print(hj);
System.out.println("head is " + hj.head.val);
}
}
ConversionConversion EmoticonEmoticon