/* Exercise 2.4 * * Partition: Write code to partition a linked list around a value x, * such that all nodes less than x come before all nodes greater than x. * If x is contained within the list, the values of x only need to be after * the elements less than x (see below). * The partition element x can appear anywhere in the "right partition;" * it does not need to appear between the left and right partitions. */ // Create a new linked list with head node newHead and tail node newTail. // O(n) runtime, O(1) space public static LinkedList.Node PartitionAround(LinkedList.Node head, int value) { if (head == null) { throw new System.ArgumentNullException("head"); } var newHead = head; var newTail = head; var currentNode = head.Next; head.Next = null; while (currentNode != null) { var nextNode = currentNode.Next; if (currentNode.data < value) { currentNode.Next = newHead; newHead = currentNode; } else { currentNode.Next = null; newTail.Next = currentNode; newTail = currentNode; } currentNode = nextNode; } return(newHead); }
public bool Solution() { int[] array = new int[] { 4, 5, 5, 4 }; LinkedList linkedList = new LinkedList(array); LinkedList reversedList = new LinkedList(array); LinkedList.Node prev = null; LinkedList.Node current = reversedList.First; while (current != null) { LinkedList.Node nextTemp = current.next; current.next = prev; prev = current; current = nextTemp; } reversedList.root = prev; LinkedList.Node linkedListNode = linkedList.First; LinkedList.Node reverseListNode = reversedList.First; while (linkedListNode.next != null && reverseListNode.next != null) { if ((int)linkedListNode.data != (int)reverseListNode.data) { return(false); } linkedListNode = linkedListNode.next; reverseListNode = reverseListNode.next; } return(true); //linkedList.printAllNodes(); //Console.WriteLine("+"); //reversedList.printAllNodes(); }
public static LinkedList sort(LinkedList list) { for (int i = 0; i < list.Count; i++) { var sorted = list.First; for (int j = 0; j < i; j++) { sorted = sorted.Next; } var current = sorted; int min = current.Data.getDimension(); current = current.Next; while (current != null) { if (current.Data.getDimension() < min) { min = current.Data.getDimension(); } current = current.Next; } LinkedList temp = list; LinkedList.Node matchingNode = temp.findMatch(min, sorted); var dummy = matchingNode.Data; matchingNode.Data = sorted.Data; sorted.Data = dummy; } return(list); }
//---------------------- static LinkedList.Node LListPartition(LinkedList.Node head, LinkedList.Node tail) { // set pivot as h element int pivot = tail.Data; // similar to i = l-1 for array implementation LinkedList.Node i = head.Prev; int temp; // Similar to "for (int j = l; j <= h- 1; j++)" for (LinkedList.Node j = head; j != tail; j = j.Next) { if (j.Data <= pivot) { // Similar to i++ for array i = (i is null) ? head : i.Next; temp = i.Data; i.Data = j.Data; j.Data = temp; } } i = (i is null) ? head : i.Next; // Similar to i++ temp = i.Data; i.Data = tail.Data; tail.Data = temp; return(i); }
/* Exercise 2.2 * * Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list. */ // Assumes last node is "0th to last." // O(n) runtime, O(1) space public static LinkedList.Node KToLast(LinkedList.Node head, int K) { if (head == null) { throw new System.ArgumentNullException("head"); } var node = head; for (int i = 0; i < K; i++) { if (node.Next == null) { throw new System.InvalidOperationException( String.Format("LinkedList does not contain at least {0} nodes", K + 1) ); } node = node.Next; } var backNode = head; while (node.Next != null) { backNode = backNode.Next; node = node.Next; } return(backNode); }
public static LinkedList AddedWith(this LinkedList.Node node1, LinkedList.Node node2) { var results = new LinkedList(); var carry = 0; while (node1 != null || node2 != null) { var node1Data = node1 == null ? 0 : node1.Data; var node2Data = node2 == null ? 0 : node2.Data; var result = node1Data + node2Data + carry; if (result >= 10) { carry = 1; result -= 10; } else { carry = 0; } results.Append(new LinkedList.Node(result)); node1 = node1?.Next; node2 = node2?.Next; } return(results); }
// Merge two sorted linked lists public static LinkedList.Node Merge(LinkedList.Node firstList, LinkedList.Node secondList) { LinkedList.Node firstLocalList = firstList; LinkedList.Node secondLocalList = secondList; if (firstLocalList == null) { return(secondLocalList); } else if (secondLocalList == null) { return(firstLocalList); } LinkedList.Node result = null; { if (firstLocalList.Value < secondLocalList.Value) { result = LinkedList.Add(result, firstLocalList.Value); result.Next = Merge(firstLocalList.Next, secondLocalList); } else if (firstLocalList.Value > secondLocalList.Value) { LinkedList.Add(result, secondLocalList.Value); result.Next = Merge(firstLocalList, secondLocalList.Next); } return(result); } }
// O(|head1|+|head2|) runtime, O(1) space public static LinkedList.Node FindIntersection(LinkedList.Node head1, LinkedList.Node head2) { // If either head node is null, throw exception. if (head1 == null) { throw new System.ArgumentNullException("head1"); } if (head2 == null) { throw new System.ArgumentNullException("head2"); } // Create array of NodeCounts to organize data. var ncArray = new NodeCount[2] { new NodeCount() { Node = head1 }, new NodeCount() { Node = head2 } }; // Calculate the length and terminating node of each list. for (int i = 0; i < ncArray.Length; i++) { ncArray[i].TerminalNode = ncArray[i].Node; while (ncArray[i].TerminalNode.Next != null) { ncArray[i].Count++; ncArray[i].TerminalNode = ncArray[i].TerminalNode.Next; } } // If the terminating nodes of the lists are not the same node, they do not intersect. if (!ncArray[0].TerminalNode.Equals(ncArray[0].TerminalNode)) { return(null); } // Sort ncArray by length of each list. ncArray = ncArray.OrderBy(x => x.Count).ToArray <NodeCount>(); // Trim the start of the longer list until they are the same length. while (ncArray[1].Count > ncArray[0].Count) { ncArray[1].Node = ncArray[1].Node.Next; ncArray[1].Count--; } // Check node-by-node until the intersecting node is found. while (ncArray[0].Node.Equals(ncArray[1].Node)) { ncArray[0].Node = ncArray[0].Node.Next; ncArray[1].Node = ncArray[1].Node.Next; } return(ncArray[0].Node); }
// Part 2 // Assumes each node contains int data. // O(n^2) runtime, O(1) space public static void RemoveDuplicates_NoBuffer(LinkedList.Node head) { if (head == null) { throw new System.ArgumentNullException("head"); } var node = head; while (node.Next != null) { var runner = node; while (runner.Next != null) { if (node.data == runner.Next.data) { runner.DeleteNext(); } else { runner = runner.Next; } } node = node.Next; } }
/* A recursive implementation of * quicksort for linked list */ public static void LinkedListQuickSort(LinkedList.Node head, LinkedList.Node tail) { if (tail != null && head != tail && head != tail.Next) { LinkedList.Node temp = LListPartition(head, tail); LinkedListQuickSort(head, temp.Prev); LinkedListQuickSort(temp.Next, tail); } }
/* Exercise <number> * * Delete Middle Node: Implement an algorithm to delete a node in the middle * (i.e., any node but the first and last node, not necessarily the exact middle) * of a singly linked list, given only access to that node. * * EXAMPLE * * Input: the node c from the linked list a -> b -> c -> d -> e -> f * Result: nothing is returned, but the new linked list looks like a -> b -> d -> e -> f */ // O(1) runtime, O(1) space public static void DeleteMiddleNode(LinkedList.Node node) { if (node.Next == null) { throw new System.ArgumentException("Cannot delete terminal node."); } node.data = node.Next.data; node.DeleteNext(); }
public static LinkedList MergeLists(LinkedList listOne, LinkedList listTwo) { LinkedList.Node firstCurrent = listOne.Head; LinkedList.Node secondCurrent = listTwo.Head; if (firstCurrent == null || secondCurrent == null) { throw new NullReferenceException("You didn't give me a list to merge!"); } // Capturing the present next nodes for use on each iteration LinkedList.Node firstListsNextNode = firstCurrent.Next; LinkedList.Node secondListsNextNode = secondCurrent.Next; // We're going down a rabbit hole while (firstCurrent.Next != null) { // Capturing each list's next node for use on this iteration firstListsNextNode = firstCurrent.Next; secondListsNextNode = secondCurrent.Next; // Insert second lists current node into next slot in first list // DON'T CHANGE -- okay, maybe needs to change for more edge cases secondCurrent.Next = firstCurrent.Next; firstCurrent.Next = secondCurrent; // Step over in first list to carry on firstCurrent = firstListsNextNode; // Step over in second list to carry on secondCurrent = secondListsNextNode; // Edge cases for breaking loop if (firstCurrent == null) { firstCurrent.Next = secondCurrent; secondCurrent = secondCurrent.Next; if (secondCurrent == null) { break; } } else if (secondCurrent == null) { firstCurrent = firstCurrent.Next; if (firstCurrent == null) { break; } } } return(listOne); }
public void UpdateRemovalOrder(int id) { var exists = this.idsToNodes.TryGetValue(id, out var existingNode); if (!exists) { existingNode = new LinkedList.Node(id); this.idsToNodes.Add(id, existingNode); } this.idsInOrderOfLastUsed.SetNodeAsHead(existingNode); }
// Version 2 // O(n^2) runtime, O(1) space public static bool IsPalindrome_NoBuffer(LinkedList.Node head) { if (head == null) { throw new System.ArgumentNullException("head"); } // If head is the only node, the linked list is a palindrome. if (head.Next == null) { return(true); } // Move through the linked list with walker and runner beginning on the 2nd node. // Each time runner steps to an odd indexed node, walker takes a step. // Each time runner steps to an even indexed node, count is incremented. var count = 0; var walker = head.Next; var runner = head.Next; while (runner.Next != null) { runner = runner.Next; walker = walker.Next; if (runner.Next != null) { count++; runner = runner.Next; } } // walker is on the first node in the second half of the linked list. // If the linked list has odd length, walker is at the node after the median (by index, not value). // count gives the number of nodes after walker to the end of the list. // backNode and forwardNode compare data in the nodes from the first half to the second half of the linked list. var backNode = head; do { var forwardNode = walker; for (int i = 0; i < count; i++) { forwardNode = forwardNode.Next; } if (forwardNode.data != backNode.data) { return(false); } count--; backNode = backNode.Next; } while (count > 0); return(true); }
static public void output(LinkedList input, StreamWriter writer) { int i = 0; LinkedList.Node current = input.First; while (i < input.Count) { i++; current.Data.write(writer); current = current.Next; } }
public void Negative() { LinkedList.Node a = new LinkedList.Node("a"); LinkedList.Node b = new LinkedList.Node("b"); LinkedList.Node c = new LinkedList.Node("c"); a.Next = b; b.Next = c; c.Next = null; LinkedList list = new LinkedList(a); Assert.IsFalse(detector.Detect(list)); }
public void PositiveHead() { LinkedList.Node a = new LinkedList.Node("a"); LinkedList.Node b = new LinkedList.Node("b"); LinkedList.Node c = new LinkedList.Node("c"); a.Next = b; b.Next = c; c.Next = a; LinkedList list = new LinkedList(a); Assert.IsTrue(detector.Detect(list)); }
// Consider a list for example as 1->2->3->4->5->7. the value returned should be 754321 public static int LinkedListToNumber(LinkedList.Node list) { int result = 0; LinkedList.Node temp = list; while (temp != null) { if (temp != null) { result = result * 10 + temp.Value; } temp = temp.Next; } return(result); }
private static LinkedList.Node FindMeetingNode(LinkedList.Node list) { LinkedList.Node p1 = list; LinkedList.Node p2 = list; while (list.Next != null || list != null || p2 != null) { list = list.Next; p2 = p2.Next.Next; if (p1 == p2) { return(p1); } } return(null); }
public void Solution() { int[] array = new int[] { 4, 5, 1, 9 }; LinkedList linkedList = new LinkedList(array); LinkedList.Node prev = null; LinkedList.Node current = linkedList.First; while (current != null) { LinkedList.Node nextTemp = current.next; current.next = prev; prev = current; current = nextTemp; } linkedList.root = prev; linkedList.printAllNodes(); }
/* Exercise 2.6 * * Palindrome: Implement a function to check if a linked list is a palindrome. */ // Verion 1 // O(n) runtime, O(n) space public static bool IsPalindrome(LinkedList.Node head) { if (head == null) { throw new System.ArgumentNullException("head"); } // If head is the only node, the linked list is a palindrome. if (head.Next == null) { return(true); } // Move through the linked list with walker and runner. // walker moves at one node per cycle, runner at two per cycle. // Each time runner can take a second step in a cycle (i.e. an even number of nodes), push walker to stack. var walker = head; var runner = head.Next; var stack = new Stack <LinkedList.Node>(); stack.Push(walker); while (runner.Next != null) { runner = runner.Next; walker = walker.Next; if (runner.Next != null) { runner = runner.Next; stack.Push(walker); } } // walker.Next is the first node in the second half of the linked list. // If the linked list has odd length, walker is on the median node (by index, not value). // Increment walker through list, compare data to popped data from stack. do { walker = walker.Next; if (walker.data != stack.Pop().data) { return(false); } } while (walker.Next != null); return(true); }
public static bool IsLoop(LinkedList.Node list) { if (list == null) { return(false); } else { LinkedList.Node head = list.Next; if (head == null) { return(false); } LinkedList.Node second = head.Next; while (second != null && head != null) { if (head == second) { return(true); } head = head.Next; second = head.Next; } while (head.Next != null || head != null || second != null) { head = head.Next; second = second.Next.Next; if (head == second) { return(true); } //if (head.Next == null || head == null || second == null) // return false; } if (head == second) { return(true); } } return(false); }
public static LinkedList.Node Find(LinkedList.Node list) { LinkedList.Node meetingnode = FindMeetingNode(list); LinkedList.Node temp = meetingnode; LinkedList.Node head = list; while (meetingnode != head) { head = head.Next; meetingnode = meetingnode.Next; } if (meetingnode == head) { return(head); } else { return(null); } }
public static LinkedList.Node nthToLast(LinkedList.Node node, int n) { LinkedList.Node curr = node; LinkedList.Node follower = node; for (int i = 0; i < n; i++) { if (curr == null) { return(null); } curr = curr.Next; } while (curr.Next != null) { curr = curr.Next; follower = follower.Next; } return(follower); }
public static void callReverseLl() { //reverse linked list LinkedList llist = new LinkedList(); llist.head = new LinkedList.Node(1); LinkedList.Node nodeA = new LinkedList.Node(2); llist.head.nextNode = nodeA; LinkedList.Node nodeB = new LinkedList.Node(3); nodeA.nextNode = nodeB; LinkedList.Node nodeC = new LinkedList.Node(4); nodeB.nextNode = nodeC; LinkedList.Node nodeD = new LinkedList.Node(5); nodeC.nextNode = nodeD; //llist.pointerReverse(); llist.callrecurrenceReverse(); }
public ArrayList displayTheListNames() { LinkedList.Node current = head; ArrayList list = new ArrayList(); if (null == head) { list.Add("There are no names on the list"); } else { while (null != current) { list.Add(current.getFirstName() + " " + current.getLastName()); current = current.nextFirstName; } } return(list); }//end displayTheListNames()
// This class is assuming the linkedlist consists of a number in reverse order // For ex. 1234 in linked list form is 4->3->2->1 public static Int64 Add(LinkedList.Node FirstList, LinkedList.Node SecondList) { Int64 secondNo = 0, firstNo = 0; if (SecondList != null) { secondNo = LinkedListToNumber(SecondList); } if (FirstList != null) { firstNo = LinkedListToNumber(FirstList); } Int64 result = firstNo + secondNo; //if(result > Int32.MaxValue) return(firstNo + secondNo); }
public static bool HasLoop(this LinkedList.Node node) { var foregerNode = node.Next; while (node != null && foregerNode != null) { if (node == foregerNode || node == foregerNode.Next) { return(true); } // Try to move the fast node forward by 2 foregerNode = foregerNode.Next != null && foregerNode.Next.Next != null ? foregerNode.Next.Next : foregerNode.Next; node = node.Next; } return(false); }
public static string DFSGeneratedStringFromGraph(Graph adjacencyList, int source) { if (source > adjacencyList.GetVertices()) { Console.WriteLine("Source entered does not exist in graph of this size. Terminating function call"); return; } Queue <int> queue = new Queue <int>(); int vertices = adjacencyList.GetVertices(); bool[] visited = new bool[vertices]; StringBuilder result = new StringBuilder(); for (int i = 0; i < vertices; i++) { visited[i] = false; } visited[source] = true; queue.Enqueue(source); while (queue.Count != 0) { int vertex = queue.Dequeue(); result.Append(vertex); LinkedList.Node current = g.GetAdjacencyList()[current].GetHead(); while (current != null) { if (!visited[current.value]) { visited[current.value] = true; queue.Enqueue(current.value); } current = current.next; } } return(result.ToString()); }
public static LinkedList.Node FirstInLoop(LinkedList.Node list) { //return new LinkedList.Node(); if (list == null) { return(null); } else { LinkedList.Node meetingNode = FindMeetingNode(list); LinkedList.Node first = list; if (meetingNode != null) { while (first != meetingNode) { first = first.Next; meetingNode = meetingNode.Next; } } return(meetingNode); } }