-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList
93 lines (80 loc) · 1.71 KB
/
LinkedList
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.*;
class Node {
int data;
Node next;
Node(int data)
{
this.data = data;
next = null;
}
}
class LinkedList {
Node head;
// Appends a new node at the end of the list
void append(int new_data){
Node new_node = new Node(new_data);
if (head == null) {
head = new_node;
return;
}
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
// Prints the contents of the linked list
void printList(){
Node node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
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;
}
void Lastfive(){
Node temp=head;
int count=0;
while(temp!=null){
System.out.print(" "+temp.data);
temp=temp.next;
count+=1;
if(count==5){
break;
}
}
}
}
public class Main {
public static void main(String[] args)
{
LinkedList obj= new LinkedList();
Scanner sc=new Scanner(System.in);
int n,data;
System.out.print("Enter the size of LL:");
n=sc.nextInt();
for(int i=0;i<n;i++){
System.out.print("Enter"+(i+1)+" element:");
data=sc.nextInt();
obj.append(data);
}
System.out.print("\nLinked list is: ");
obj.printList();
obj.reverse();
System.out.println("\nAfter reversing:");
obj.printList();
System.out.println("\nLast Five elements are:");
obj.Lastfive();
}
}