-
Notifications
You must be signed in to change notification settings - Fork 181
/
LL.java
129 lines (119 loc) · 2.01 KB
/
LL.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class Node
{
private int data;
public Node next;
public Node(int data)
{
this.data=data;
this.next=null;
}
public int getData()
{
return this.data;
}
}
class LinkedList
{
private Node head;
private Node tail;
public int size;
public LinkedList()
{
head=null;
tail=null;
size=0;
}
public boolean isEmpty()
{
return head==tail;
}
public int getSize()
{
return size;
}
public void insertAtStart(int val)
{
Node newNode = new Node(val);
size++ ;
if(head == null)
{
head = newNode;
tail = head;
}
else
{
newNode.next=head;
head=newNode;
}
}
public void insertAtLast(int val)
{
Node newNode=new Node(val);
size++;
if(head==null)
{
head=newNode;
tail=newNode;
}
else
{
tail.next=newNode;
tail=newNode;
}
}
public void insertAtPos(int val, int pos)
{
Node newNode= new Node(val);
Node temp=head;
pos=pos-1;
for(int i=0;i<size;i++)
{
if(i==pos)
{
Node temp1=temp.next;
temp.next=newNode;
newNode.next=temp1;
break;
}
temp=temp.next;
}
size++;
}
public void delete(int pos)
{
if (pos == 1)
{
head=head.next;
size--;
return ;
}
if (pos == size)
{
Node prev = head;
Node temp = head;
while (temp.next!=null)
{
prev=temp;
temp=temp.next;
}
tail=prev;
prev.next=null;
size --;
return;
}
Node ptr = head;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.next;
tmp = tmp.next;
ptr.next=temp;
break;
}
ptr = ptr.next;
}
size-- ;
}
}