Skip to content

Commit 9bfc445

Browse files
committed
added linkedlist operations
1 parent dcd04a1 commit 9bfc445

File tree

1 file changed

+69
-1
lines changed

1 file changed

+69
-1
lines changed

LinkedList/SinglyLinkedList.java

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ private ListNode insertInSortedList(int value) {
154154
return head;
155155
}
156156

157-
private void getNthNodeFromEnd(int n) {
157+
private void getNthNodeFromEnd1(int n) {
158158

159159
if(head == null) {
160160

@@ -189,6 +189,26 @@ private void getNthNodeFromEnd(int n) {
189189
System.out.println(mainPtr.data);
190190
}
191191

192+
private static int getNthNodeFromEnd2(int positionFromTail) {
193+
int index = 0;
194+
195+
ListNode current = head;
196+
ListNode result = head;
197+
198+
while(current != null)
199+
{
200+
current = current.next;
201+
202+
if(index > positionFromTail)
203+
{
204+
result=result.next;
205+
}
206+
index++;
207+
}
208+
209+
return result.data;
210+
}
211+
192212
private ListNode reverseList() {
193213

194214
ListNode current = head;
@@ -251,6 +271,54 @@ private boolean detectLoop() {
251271
return false;
252272
}
253273

274+
275+
static boolean compareLists(ListNode head1, ListNode head2) {
276+
277+
ListNode current1 = head1;
278+
ListNode current2 = head2;
279+
280+
int length1 = 0;
281+
int length2 = 0;
282+
283+
while(current1 != null && current2 != null) {
284+
if(current1.data != current2.data) {
285+
return false;
286+
}
287+
length1++;
288+
length2++;
289+
290+
current1 = current1.next;
291+
current2 = current2.next;
292+
}
293+
294+
return length1 == length2;
295+
296+
}
297+
298+
public static ListNode removeDuplicates(ListNode head) {
299+
300+
// if list is empty or if list contains a single node
301+
if(head == null || head.next == null){
302+
return head;
303+
}
304+
305+
// having a reference for head node and then manipulating it further
306+
ListNode current = head;
307+
308+
// if head's next is null, it's the end of list
309+
while(head.next!=null){
310+
// checking head's data with it's next data
311+
if(head.data != head.next.data){
312+
head = head.next;
313+
}else{
314+
head.next = head.next.next;
315+
}
316+
}
317+
318+
return current;
319+
}
320+
321+
254322
public static void main(String[] args) {
255323

256324
SinglyLinkedList sll = new SinglyLinkedList();

0 commit comments

Comments
 (0)