-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPrintLinkedList.java
98 lines (89 loc) · 1.9 KB
/
PrintLinkedList.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
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
94
95
96
97
98
/*
* Print is a Linked List
*
*/
public class PrintLinkedList {
// creat Node
public static class Node{
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
}
public static Node head;
public static Node tail;
// Add first
public static void addFirst(int data){
Node nextNode = new Node(data);
if (head == null) {
head=tail=nextNode;
return;
}
nextNode.next = head;
head = nextNode;
}
// Add list
public static void addLast(int data){
Node nextNode = new Node(data);
if (head == null) {
head=tail=nextNode;
return;
}
tail.next = nextNode;
tail = nextNode;
}
// print Linked list
public static void printLL(){
if (head==null) {
System.out.println("Linked List is a Empty");
return;
}
Node temp = head;
while(temp!=null){
System.out.print(temp.data +"->");
temp = temp.next;
}
System.out.println("null");
}
public static void main(String[] args) {
printLL();
addFirst(4);
printLL();
addFirst(6);
printLL();
addFirst(7);
printLL();
addFirst(8);
printLL();
addFirst(9);
printLL();
addLast(3);
printLL();
addLast(2);
printLL();
addLast(1);
printLL();
addLast(0);
printLL();
addFirst(10);
printLL();
}
}
/*
* OutPut
*
* Linked List is a Empty
* 4->null
* 6->4->null
* 7->6->4->null
* 8->7->6->4->null
* 9->8->7->6->4->null
* 9->8->7->6->4->3->null
* 9->8->7->6->4->3->2->null
* 9->8->7->6->4->3->2->1->null
* 9->8->7->6->4->3->2->1->0->null
* 10->9->8->7->6->4->3->2->1->0->null
*
*/