Last active
January 10, 2021 05:03
-
-
Save mrshridhara/6c26acb49ae1bc29f98a to your computer and use it in GitHub Desktop.
LinkedList manipulations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LinkedListNode | |
{ | |
public int val; | |
public LinkedListNode next; | |
} | |
public class LinkedListHelper | |
{ | |
public static LinkedListNode MergeLinkedLists(LinkedListNode head1, LinkedListNode head2) | |
{ | |
if (head1 == head2 == null) | |
{ | |
return null; | |
} | |
if (head1 == null) | |
{ | |
return head2; | |
} | |
if (head2 == null) | |
{ | |
return head1; | |
} | |
if (head1.val >= head2.val) | |
{ | |
head1 = new LinkedListNode { val = head2.val, next = head1 }; | |
head1.next = MergeLinkedLists(head1.next, head2.next); | |
} | |
else | |
{ | |
head1.next = MergeLinkedLists(head1.next, head2); | |
} | |
return head1; | |
} | |
public static LinkedListNode RemoveInteger(LinkedListNode head, int intToRemove) | |
{ | |
if (head == null) | |
{ | |
return null; | |
} | |
while (head.val == intToRemove) | |
{ | |
head = head.next; | |
} | |
if (head.next != null) | |
{ | |
head.next = RemoveInteger(head.next, intToRemove); | |
} | |
return head; | |
} | |
public static LinkedListNode InsertInteger(LinkedListNode head, int intToInsert) | |
{ | |
if (head == null) | |
{ | |
return null; | |
} | |
if (head.val > intToInsert) | |
{ | |
return new LinkedListNode { val = intToInsert, next = head }; | |
} | |
if (head.next == null) | |
{ | |
head.next = new LinkedListNode { val = intToInsert }; | |
} | |
else if (head.next.val >= intToInsert) | |
{ | |
var nextToMove = head.next; | |
head.next = new LinkedListNode { val = intToInsert, next = nextToMove }; | |
} | |
else | |
{ | |
head.next = InsertInteger(head.next, intToInsert); | |
} | |
return head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment