-
Notifications
You must be signed in to change notification settings - Fork 9
/
PrintInReverse.java
34 lines (29 loc) Β· 900 Bytes
/
PrintInReverse.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package linkedlist;
import java.util.Scanner;
public class PrintInReverse {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Node head = new Node();
head.input(1);
head.print();
head = reverseLL(head);
System.out.println("");
head.print();
}
private static Node reverseLL(Node head){
if(head.size() <= 1)
return head;
else if (head.size() == 2) {
Node temp = head.next;
temp.next = head;
head.next = null;
return temp;
}
Node first, second, third;
for(first = head, second = first.next, third = second.next, first.next = null ; third != null ; first = second, second = third, third = third.next){
second.next = first;
}
second.next = first;
return second;
}
}