-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.java
98 lines (95 loc) · 1.97 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
package list;
public class LinkedList {
Node head;
static class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
public void insertAtLast(int data) {
Node toAdd=new Node(data);
Node temp=head;
if(head==null) {
head=toAdd;
return;
}
while(temp.next!=null) {
temp=temp.next;
}
temp.next=toAdd;
}
public void insertAtBeg(int data) {
Node toAdd=new Node(data);
Node temp=head;
if(head==null) {
head=toAdd;
}
head=toAdd;
head.next=temp;
}
public void insertAtPos(int data,int key) {
Node temp=head;
while(temp.data!=key) {
temp=temp.next;
}
temp.data=key;
}
public void merge(LinkedList ll,LinkedList lll) {
Node curr=ll.head;
Node last=lll.head;
while(curr.next!=null) {
curr=curr.next;
}
curr.next=last;
}
public boolean search(LinkedList ll,int d) {
Node curr=head;
while(curr!=null) {
if(curr.data==d)
return true;
curr=curr.next;
}
return false;
}
public void removeLast() {
Node temp=head;
//Node toRemove=head;
if(temp==null) {
System.out.println("cannot remove from empty node");
return;}
if(temp.next==null) {
head=null;
}
while(temp.next.next!=null) {
temp=temp.next;
}
temp.next=null;
}
Node deleteNode(Node head, int position) {
Node curr=head;
Node prev=head;
Node last=null;
if (position == 0) {
head = curr.next;
return head;
}
while(position>0){
prev=curr;
curr=curr.next;
position--;
}
last=curr.next;
prev.next=last;
return head;
}
void print() {
Node temp=head;
while(temp!=null) {
System.out.println(temp.data+" ");
temp=temp.next;
}
}
}