-
Notifications
You must be signed in to change notification settings - Fork 0
/
LLDemo2.java
139 lines (127 loc) · 2.5 KB
/
LLDemo2.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
130
131
132
133
134
135
136
137
138
139
class SLinkList
{
private class Node
{
private int data;
private Node link;
Node()
{
data=0;
head=null;
}
Node(int newdata,Node newlink)
{
setData(newdata);
link=newlink;
}
void setData(int new_data){data=new_data;}
void setLink(Node new_link){link=new_link;}
int getData(){return data;}
Node getLink(){return link;}
}
protected Node head;
SLinkList(){head=null;}
public void addToHead(int value){head=new Node(value,head);}
public int size()
{
Node pos=head;
int count=0;
while(pos!=null)
{
count++;
pos=pos.getLink();
}
return count;
}
public void addToLast(int value)
{
Node pos=head;
if(head==null) {addToHead(value);}
else
{
while(pos!=null)
pos=pos.getLink();
pos.link=new Node(value,pos.getLink()) ;
return ;
}
}
public void display()
{
Node pos=head;
while(pos!=null)
{
System.out.print(pos.getData()+"<-");
pos=pos.getLink();
}
System.out.println("Null");
}
public void insertAfter(int key,int toins)
{
Node pos=head;
while(pos!=null && pos.getData()!=key)
{
pos=pos.getLink();
}
if(pos!=null)
pos.link=new Node(toins,pos.link);
}
public void insertBefore(int key ,int toins)
{
Node prev=null;
Node curr=head;
if(curr==null)return ;
if(head.getData()==toins)
{
addToHead(toins);
return ;
}
while(curr!=null && curr.getData()!=key)
{
prev=curr;
curr=curr.getLink();
}
if(curr!=null)
{
prev.link=new Node(toins,curr);
}
}
public void deleteNode(int key)
{
Node prev=null;
Node curr=head;
if(curr.getData()==key)
{
head=curr.link;
return ;
}
if(curr == null) return;
while(curr!=null && curr.getData()!=key)
{
prev=curr;
curr=curr.getLink();
}
if(curr!=null)
{
prev.link=curr.link;
}
}
}
class LLDemo2
{
public static void main(String []args)
{
SLinkList lst=new SLinkList();
for(int i=1;i<=10;++i)
{
lst.addToHead(i);
}
lst.display();
//lst.addToLast(0);
System.out.println(lst.size());
lst.insertAfter(5,11);
lst.insertBefore(4,12);
lst.display();
lst.deleteNode(6);
lst.display();
}
}