-
Notifications
You must be signed in to change notification settings - Fork 0
/
complete_list_insertion.java
86 lines (74 loc) · 1.91 KB
/
complete_list_insertion.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
//insertion in a linked list
public class Completeinsertion
{
Node head;
static class Node
{
int data;
Node next;
Node(int d)
{
data=d;
next=null;
}
}
//function to insert in front
public void front(int element)
{
Node new_node = new Node(element); //allocates new node
new_node.next=head; //new node becomes the head
head=new_node; //now head points the new node
}
//function to insert after a given specific node
public void between(Node pre_node, int element)
{
if(pre_node == null)
{
System.out.println("Previous node can't be null !!");
return;
}
Node new_node = new Node(element);
new_node.next=pre_node.next;
pre_node.next=new_node;
}
//function to insert at the end
public void end(int element)
{
Node new_node = new Node(element);
if(head==null)
{
head=new Node(element); //if list is empty
return;
}
new_node.next=null;
Node last=head;
while(last.next!=null) //traversal till the last node.
{
last=last.next;
}
last.next=new_node;
return;
}
//print function
public void print()
{
Node n=head;
while(n!=null)
{
System.out.print(n.data+" ");
n=n.next;
}
}
//finally the main function
public static void main(String args[])
{
Completeinsertion ci = new Completeinsertion();
ci.end(5); //start with empty list
ci.front(2);
ci.front(1);
ci.end(6);
ci.between(ci.head.next, 3); //at the third position.
System.out.println("\nCurrent Linked List: ");
ci.print();
}
}