-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathLinkedList.java
113 lines (106 loc) · 2.64 KB
/
LinkedList.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.*;
public class LinkedList
{
static class Node{
int data;
Node next;
}
static class Single{
static Node head;
static Node tail;
static int size;
public static Node create(int value)
{
head = new Node();
Node node = new Node();
node.next = null;
node.data = value;
head = node;
tail = node;
size = 1;
return head;
}
public static void Insert(int value, int p)
{
Node node = new Node();
node.data = value;
if(head == null)
{
create(value);
return;
}
else if(p == 0)
{
node.next = head;
head = node;
}
else if(p >=size)
{
node.next = null;
tail.next = node;
tail = node;
}
else{
Node temp = head;
int i=0;
while(i<p-1)
{
temp = temp.next;
i++;
}
Node nextN = temp.next;
temp.next = node;
node.next = nextN ;
}
size++;
}
//traversal
public static void traverse()
{
if(head == null)
{
System.out.println("Empty");
}
else{
Node temp = head;
for(int i=0;i<size;i++)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
}
System.out.println();
}
public static void reverse()
{
if(head.next == null || head == null)
{
return;
}
Node prev = head;
Node current = head.next;
while(current != null)
{
Node nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
}
head.next = null;
head = prev;
}
}
public static void main(String args[])
{
Single list = new Single();
list.create(5);
list.Insert(6, 1);
list.Insert(4, 2);
list.Insert(11, 3);
list.Insert(7, 4);
//System.out.println(list.head.next.data);
list.traverse();
list.reverse();
list.traverse();
}
}