-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathsinglylinkedlist.java
More file actions
89 lines (83 loc) · 2.01 KB
/
singlylinkedlist.java
File metadata and controls
89 lines (83 loc) · 2.01 KB
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
//Singly linked list implemented using java
class singlylinkedlist{
Node head;
class Node{
int data;
Node next;
// make constructor of node class
Node( int data){
this.data=data;
}
}
// method to add at head of linked list
public void addfirst(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
}
else{
newNode.next=head;
head=newNode;
}
}
//method to add at last of linked list
public void addlast(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
}
else{
Node currNode=head;
while(currNode.next!=null){
currNode=currNode.next;
}
currNode.next=newNode;
}
}
//method to delete first element of linked list
public void deletefirst(){
if(head==null){
System.out.println("Empty");
}
else{
head=head.next;
}
}
// method to delete last element of linked list
public void deletelast(){
if(head==null){
System.out.println("Empty linked list");
}
if(head.next==null){
head=null;
}
else{
Node currNode=head.next;
Node prevNode=head;
while(currNode.next!=null){
currNode=currNode.next;
prevNode=prevNode.next;
}
prevNode.next=null;
}
}
// method to print linked list
public void print(){
Node currNode=head;
while(currNode!=null){
System.out.println(currNode.data);
currNode=currNode.next;
}
System.out.println("null");
}
public static void main(String args[]){
singlylinkedlist ob=new singlylinkedlist();
ob.addfirst(10);
ob.addfirst(20);
ob.addlast(30);
ob.addlast(40);
ob.deletefirst();
ob.deletelast();
ob.print();
}
}