public void ReverseSingleSublistTest() { Func<ListNode<int>, int, int, ListNode<int>>[] functions = new Func<ListNode<int>, int, int, ListNode<int>>[] { ReverseSingleSublist.BruteForce, ReverseSingleSublist.SinglePass }; for(int i = 0; i < 10; i++) { int[] data = ArrayUtilities.CreateRandomArray(10, 0, 10); for (int start = 1; start <= 10; start++) { for(int end = start; end <= 10; end++) { ListNode<int>[] results = new ListNode<int>[functions.Length]; for (int j = 0; j < results.Length; j++) { ListNode<int> head = LinkedListUtilities.Initialize(data); results[j] = functions[j](head, start, end); Assert.IsTrue(LinkedListUtilities.AreEqual(results[0], results[j])); } } } } }
public ListNode<int> RemoveNthFromEnd(ListNode<int> head, int n) { // assume the input is always valid if (head.Next == null) // only 1 node { return null; } // reach that node first var tail = head; var preDelete = head; for (int i = 0; i < n; i++) { tail = tail.Next; } if (tail == null) // toDelete is head { return head.Next; } while (tail.Next != null) { tail = tail.Next; preDelete = preDelete.Next; } preDelete.Next = preDelete.Next.Next; return head; }
private ListNode MergeTwoLinkedList(ListNode node1, ListNode node2) { ListNode result = new ListNode(0); ListNode pointer = result; while (node1 != null && node2 != null) { if (node1.val < node2.val) { pointer.next = node1; node1 = node1.next; } else { pointer.next = node2; node2 = node2.next; } pointer = pointer.next; } while (node1 != null) { pointer.next = node1; node1 = node1.next; pointer = pointer.next; } while (node2 != null) { pointer.next = node2; node2 = node2.next; pointer = pointer.next; } return result.next; }
public static ListNode Process(ListNode head, uint k) { if (head == null || k == 0) { return null; } ListNode ahead = head; for (int i = 0; i < k - 1; ++i) { if (ahead.Next != null) { ahead = ahead.Next; } else { return null; } } ListNode behind = head; while (ahead.Next != null) { ahead = ahead.Next; behind = behind.Next; } return behind; }
public ListNode<int> RotateRight(ListNode<int> head, int n) { if (head == null) { return null; } int totalLength = 1; ListNode<int> tail = head; while (tail.Next != null) { totalLength++; tail = tail.Next; } n %= totalLength; if (n == 0) { return head; } ListNode<int> p = head; for (int i = 0; i < totalLength - n - 1; i++) { p = p.Next; } ListNode<int> newHead = p.Next; p.Next = null; tail.Next = head; return newHead; }
public ListNode<int> RotateRight(ListNode<int> head, int n) { if (head == null) { return null; } // calc length first int length = 1; var tail = head; while (tail.Next != null) { length++; tail = tail.Next; } if (length <= 1) { return head; } n = n % length; if (n == 0) { return head; } var newTail = head; for (int i = 0; i < length - 1 - n; i++) { newTail = newTail.Next; } tail.Next = head; head = newTail.Next; newTail.Next = null; return head; }
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { int a = 0; int b = 0; bool needUpOne = false; ListNode result = new ListNode(0); ListNode TempNode = result; while (l1 != null || l2 != null || needUpOne) { a = b = 0; if (l1 != null) { a = l1.val; l1 = l1.next; } if (l2 != null) { b = l2.val; l2 = l2.next; } TempNode.next = new ListNode(a + b + (needUpOne ? 1 : 0)); TempNode = TempNode.next; needUpOne = TempNode.val >= 10; TempNode.val -= (needUpOne ? 10 : 0); } return result.next; }
private static void Print(ListNode n) { if(n != null){ Console.Write(n.val); Print(n.next); } }
public ListNode RotateRight(ListNode head, int k) { if (k <= 0 || head == null) { return head; } var ptr = new ListNode(-1); ptr.next = head; int lenght = 0; while (ptr.next != null) { ptr = ptr.next; lenght++; } ptr.next = head; var rest = lenght - k % lenght; for (int i = 0; i < rest; i++) { ptr = ptr.next; } head = ptr.next; ptr.next = null; return head; }
public ListNode MergeKLists1(ListNode[] lists) { ListNode result = new ListNode(0); ListNode pointer = result; MinHeap mh = new MinHeap(); foreach (ListNode node in lists) { if (node != null) { mh.Add(node); } } while (mh.Count > 0) { ListNode node = mh.PopMin(); if (node.next != null) { mh.Add(node.next); } pointer.next = node; pointer = pointer.next; } return result.next; }
private static ListNode<int> SinglePass(ListNode<int> a, ListNode<int> b) { ListNode<int> head = a.Value >= b.Value ? a : b; ListNode<int> tail = head; while(a != null && b != null) { ListNode<int> next = null; if (a.Value <= b.Value) { next = a; a = a.Next; } else { next = b; b = b.Next; } tail.Next = next; tail = next; } tail.Next = a ?? b; return head; }
public ListNode ReverseBetween(ListNode head, int m, int n) { var length = n-m +1; if(m == 1){ ListNode tail; var h = ReverseList(head, length, out tail); head.next = tail; return h; } else{ var c = 2; var t = head; while(c != m){ t = t.next; c++; } ListNode tail; var h = ReverseList(t.next, length, out tail); t.next.next = tail; t.next = h; return head; } }
public ListNode<int> ReverseBetween(ListNode<int> head, int m, int n) { if (m == n) { return head; } // find pre-changing head ListNode<int> dummy = new ListNode<int>(0); dummy.Next = head; var preChaningHead = dummy; int changeLength = n - m; while (m-- > 1) { preChaningHead = preChaningHead.Next; } var curNode = preChaningHead.Next; for (int i = 0; i < changeLength; i++) { var preNext = preChaningHead.Next; var curNext = curNode.Next; curNode.Next = curNext.Next; preChaningHead.Next = curNext; curNext.Next = preNext; } return dummy.Next; }
public ListNode<int> ReverseBetween2(ListNode<int> head, int m, int n) { ListNode<int> newHead = new ListNode<int>(-1); newHead.Next = head; ListNode<int> preTail = newHead; int index = 1; while (index < m) { preTail = head; head = head.Next; index++; } ListNode<int> reversedHead = new ListNode<int>(-1); ListNode<int> reversedTail = reversedHead; while (index <= n) { reversedHead.Val = head.Val; ListNode<int> temp = new ListNode<int>(-1); temp.Next = reversedHead; reversedHead = temp; head = head.Next; index++; } reversedTail.Next = head; preTail.Next = reversedHead.Next; return newHead.Next; }
public ListNode ReverseBetween(ListNode head, int m, int n) { ListNode part1Head = null; ListNode part1Tail = null; for (var i = 1; i < m; ++i) { if (part1Head == null) { part1Head = head; } part1Tail = head; head = head.next; } if (part1Tail != null) part1Tail.next = null; ListNode part2Head = null; ListNode part2Tail = null; for (var i = m; i <= n; ++i) { var next = head.next; head.next = part2Head; part2Head = head; if (part2Tail == null) { part2Tail = head; } head = next; } if (part1Tail != null) { part1Tail.next = part2Head; } part2Tail.next = head; return part1Head ?? part2Head; }
public override void Clear() { ClearHash(); list_start = null; list_end = null; base.Clear(); }
public ListNode detectCycle(ListNode a) { if (a == null) return null; ListNode i = a; // note: they start at the same point. Count travel distance by edge, not node!!! Slow pointer travels x edges -> fast pointer travels 2x edges ListNode j = a; while (j != null) { i = i.next; if (j.next != null) j = j.next.next; // note: list doesn't have cycle if j becomes null else break; if (i == j) // when i meets j, they have to meet inside the cycle (this doesn't have to be the starting point of the cycle) { i = a; while (i != j) { i = i.next; j = j.next; } return i; } } return null; }
private static void AddTwoNumbers() { ListNode num1 = new ListNode(2); num1.next = new ListNode(4); num1.next.next = new ListNode(3); ListNode num2 = new ListNode(5); num2.next = new ListNode(6); num2.next.next = new ListNode(4); ListNode num3 = new ListNode(5); ListNode num4 = new ListNode(5); ListNode num5 = new ListNode(1); num5.next = new ListNode(8); ListNode num6 = new ListNode(0); var a = new LeetCodeOJ154.Solution(); timer.Restart(); ListNode result = a.AddTwoNumbers(num5, num6); timer.Stop(); while (result!=null) { Console.WriteLine(result.val); result = result.next; } Console.WriteLine("耗时{0}毫秒", timer.ElapsedMilliseconds); }
public static void Process(ref ListNode head, ListNode toBeDeleted) { if (head == null || toBeDeleted == null) { return; } if (toBeDeleted.Next != null) { toBeDeleted.Value = toBeDeleted.Next.Value; toBeDeleted.Next = toBeDeleted.Next.Next; } else if (toBeDeleted == head) { head = null; } else { ListNode current = head; while (current.Next != toBeDeleted) { current = current.Next; } current.Next = null; } }
public ListNode InsertionSortList(ListNode head) { ListNode preHead = new ListNode(Int.MinValue); preHead.next = head; ListNode prev = null; //points to the node before curr ListNode curr = head; while(curr!=null){ ListNode newPrev = curr; //if curr won't be moved, the prev for next pass ListNode newCurr = curr.next; //if curr won't be moved, the curr for next pass ListNode p = preHead; while(p.next!=curr){ if(curr.val>=p.val && curr.val<=p.next.val){//curr needs ot be inserted between p and p.next ListNode temp = curr.next; //store original curr.next curr.next = p.next; //insert curr p.next = curr; prev.next = temp; //after removing curr, needs to connect prev and original curr.next newPrev = prev; //curr is moved so prev for next pass doesn't change break; } p=p.next; } prev=newPrev; //if curr is not moved, prev won't change, otherwiese, prev points to curr curr=newCurr; //curr would always points to curr.next } return preHead.next; }
public ListNode ReverseBetween(ListNode head, int m, int n) { if(head==null) return null; //handle edge case ListNode preHead = new ListNode(0); preHead.next = head; ListNode start = preHead; //start will be the (m-1)th node in the list //advance start pointer to the (m-1)th node in the list int count = 1; while(start!=null && count<m){ start = start.next; count++; } if(count<m) return head; //length of the list is smaller than m, edge case //end is the mth node in the list ListNode end = start.next; //node will be inserted between start and end ListNode curr = end.next;//curr is the node to be insert //insert each node right after start, advance curr until count==n while(curr!=null && count<n){ ListNode next = curr.next; //get the next node using curr.next curr.next = start.next; //insert curr right after start node start.next = curr; end.next = next; //point end to next node curr = next; //advance curr to next node count++; } return preHead.next; //preHead is the node before original head, so return preHead.next }
public ListNode<int> SwapPairs(ListNode<int> head) { if (head == null || head.Next == null) { return head; } ListNode<int> preResult = new ListNode<int>(-9999); // helper node var pre = preResult; var n1 = head; var n2 = head.Next; var post = n2.Next; while (true) { pre.Next = n2; n2.Next = n1; n1.Next = post; if (post == null || post.Next == null) { break; } pre = n1; n1 = post; n2 = n1.Next; post = n2.Next; } return preResult.Next; }
public static void Main() { //test#1: null ListNode head = null; Solution.display(Solution.removeNodes(head,5)); //empty //test#2: 1 head = new ListNode(1); Solution.display(Solution.removeNodes(head,5)); //1-> //test#3: 5 head = new ListNode(5); Solution.display(Solution.removeNodes(head,5)); //empty //test#4: 1->2 head = new ListNode(1); head.next = new ListNode(2); Solution.display(Solution.removeNodes(head,5)); //1->2-> //test#5: 5->5->5 head = new ListNode(5); head.next = new ListNode(5); head.next.next = new ListNode(5); Solution.display(Solution.removeNodes(head,5)); //empty //test#6: 1->2->5->5 head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(5); head.next.next.next = new ListNode(5); Solution.display(Solution.removeNodes(head,5)); //1->2-> //test#7: 1->2->5->5->3 head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(5); head.next.next.next = new ListNode(5); head.next.next.next.next = new ListNode(3); Solution.display(Solution.removeNodes(head,5)); //1->2->3-> }
public ListNode DeleteDuplicates(ListNode head) { if(head==null||head.next==null) return head; ListNode preHead=new ListNode(-1); preHead.next=head; ListNode first=preHead; ListNode second=head; bool isDuplicate=false; while(second.next!=null) { if(first.next.val==second.next.val) { second=second.next; isDuplicate=true; } else{ if(isDuplicate) { first.next=second.next; second=second.next; } else{ first=first.next; second=second.next; } isDuplicate=false; } } if(isDuplicate) { first.next=null; } return preHead.next; }
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { var add1=Convert(l1); var add2=Convert(l2); var res=add1+add2; return Convert(res); }
//method to merge two sorted lists private ListNode MergeTwoLists(ListNode l1, ListNode l2){ if(l1==null||l2==null){ if(l1 ==null) return l2; if(l2 ==null) return l1; } ListNode newHead,p,p1,p2; if(l1.val < l2.val){ newHead = l1; p1 = l1.next; p2 = l2; } else{ newHead = l2; p1 = l1; p2 = l2.next; } p = newHead; while(p1!=null && p2!=null){ if(p1.val < p2.val){ p.next = p1; p1 = p1.next; } else{ p.next = p2; p2 = p2.next; } p=p.next; } //no need to use the while loop, directly append p1 or p2 to p //because rest nodes of p1 or p2 are already sorted if(p1!=null) p.next=p1; if(p2!=null) p.next=p2; return newHead; }
public ListNode<int> AddTwoNumbers(ListNode<int> l1, ListNode<int> l2) { ListNode<int> current = new ListNode<int>(-1); ListNode<int> head = current; int carry = 0; while (l1 != null || l2 != null || carry > 0) { int result = carry; if (l1 != null) { result += l1.Val; l1 = l1.Next; } if (l2 != null) { result += l2.Val; l2 = l2.Next; } current.Next = new ListNode<int>(result % 10); current = current.Next; carry = result / 10; } return head.Next; }
public ListNode<int> Partition(ListNode<int> head, int x) { if (head == null) return null; ListNode<int> first = new ListNode<int>(-1); ListNode<int> second = new ListNode<int>(-1); ListNode<int> originalFirst = first; ListNode<int> originalSecond = second; while (head != null) { if (head.Val < x) { first.Next = head; first = first.Next; } else { second.Next = head; second = second.Next; } head = head.Next; } second.Next = null; first.Next = originalSecond.Next; return originalFirst.Next; }
public ListNode<int> AddTwoNumbers(ListNode<int> l1, ListNode<int> l2) { // add l2 on to l1 ListNode<int> current = new ListNode<int>(0); var answer = current; int toAdd = 0; while (true) { current.Val += toAdd; if (l1 != null) { current.Val += l1.Val; l1 = l1.Next; } if (l2 != null) { current.Val += l2.Val; l2 = l2.Next; } toAdd = current.Val / 10; current.Val = current.Val % 10; if (l1 != null || l2 != null || toAdd > 0) { current.Next = new ListNode<int>(0); current = current.Next; } else { break; } } return answer; }
public void DeleteNode(ListNode node) { if (node == null) return; node.val = node.next.val; node.next = node.next.next; return; }
private ListNode Reverse(ListNode prev, int n) { ListNode head = prev.Next, current = head, next = null; while (current != null && n >= 0) { next = current.Next; current.Next = prev; prev = current; current = next; n--; } // The nth node is new next node of head. head.Next = current; return(prev); }
public ListNode DeleteNode(ListNode head, int val) { ListNode p = head; while (p != null) { if (p.val == val) // 删除首节点值相等情况 { return(p.next); } if (p.next != null && p.next.val == val) { p.next = p.next.next; break; } p = p.next; } return(head); }
private ListNode breakListInMiddle(ListNode head) { if (head?.next == null) { return(null); } ListNode slow = head, fast = head.next; while (fast?.next != null) { slow = slow.next; fast = fast.next.next; } ListNode secondHead = slow.next; slow.next = null; return(secondHead); }
public static bool HasCycle(ListNode head) { var p1 = head; var p2 = head; while (p1 != null && p2 != null) { p1 = p1.next; if (p1 == null) return false; if (p2.next == null) return false; p2 = p2.next.next; if (p2 == null) return false; if (p1 == p2) { return true; } } return false; }
public int GetDecimalValue(ListNode head) { int len = -1; int num = 0; ListNode temp = head; while (temp != null) { len++; temp = temp.next; } temp = head; while (temp != null) { num = num + temp.val * Convert.ToInt32(Math.Pow(2, len)); len--; temp = temp.next; } return(num); }
public ListNode RevertList(ListNode listNode, out int len) { var header = new ListNode(-1); var ptr = listNode; len = 0; while (ptr != null) { len++; var node = ptr; ptr = ptr.next; node.next = header.next; header.next = node; } return(header.next); }
//A closed scope binds variables at the point of definition //construct a new closed scope, only referenced bindings public Scope CloseScope(ListNode body) { var identifierNodes = body.IdentifierNodes(); var referencedNames = identifierNodes.Select(i => i.Name).ToHashSet(); Scope closedScope = new Scope { Usings = Usings.ToList() }; foreach (string name in referencedNames) { Binding binding = GetBinding(name); if (binding != null) { closedScope.BoundVariables.Add(name, binding); } } return(closedScope); }
public T RemoveAt(int index) { if (index >= count || index < 0) { throw new ArgumentOutOfRangeException("Invalid index: " + index); } int currentIndex = 0; ListNode currentNode = head; ListNode prevNode = sentinel; while (currentIndex < index) { prevNode = currentNode; currentNode = currentNode.NextNode; currentIndex++; } RemoveListNode(currentNode, prevNode); return(currentNode.Element); }
static void Main(string[] args) { var solve = new Solution(); ListNode head = new ListNode(0); ListNode cNode = head; for (int i = cNode.val + 1; i <= 5; i++) { cNode.next = new ListNode(i); cNode = cNode.next; } head = solve.ReverseList(head); while (head != null) { Console.WriteLine($"{head.val}"); head = head.next; } }
private ListNode findMiddleElement(ListNode head) { ListNode prevPtr = null; ListNode slowPtr = head; ListNode fastPtr = head; while (fastPtr != null && fastPtr.next != null) { prevPtr = slowPtr; slowPtr = slowPtr.next; fastPtr = fastPtr.next.next; } if (prevPtr != null) { prevPtr.next = null; } return(slowPtr); }
public int countRunningContext() { lock (this.mQueueLock) { if (this.mContextQueue.isEmpty()) { return(0); } int num = 0; for (ListNode node = this.mContextQueue._head._next; node != null; node = node._next) { TContext local = (TContext)node._obj; if ((local != null) && local.isRunning()) { num++; } } return(num); } }
public bool HasCycle(ListNode head) { if (head == null) { return(false); } ListNode slow = head; ListNode fast = head.next; while (fast != null && fast.next != null) { if (fast.val == slow.val) { return(true); } fast = fast.next.next; slow = slow.next; } return(false); }
public ListNode RemoveNthFromEnd(ListNode head, int n) { var first = head; var second = head; for (int i = 0; i < n; i++) { second = second.next; } while (second.next != null) { first = first.next; second = second.next; } first.next = first.next.next; return(head); }
public ListNode RemoveElements(ListNode head, int val) { ListNode header = new ListNode(-1); header.next = head; ListNode cur = header; while (cur.next != null) { if (cur.next.val == val) { cur.next = cur.next.next; } else { cur = cur.next; } } return(header.next); }
/** value will always be non-negative. */ public void Put(int key, int value) { int i = GetIndexByKey(key); if (nodes[i] == null) { nodes[i] = new ListNode(-1, -1); } var prev = GetPreviousNode(nodes[i], key); if (prev.next == null) { prev.next = new ListNode(key, value); } else { prev.next.val = value; } }
public T RemoveLast() { if (this.Count == 0) { throw new InvalidOperationException("List empty"); } var lastElement = this.tail.Value; this.tail = this.tail.PrevNode; if (this.tail != null) { this.tail.NextNode = null; } else { this.head = null; } this.Count--; return(lastElement); }
/** * https://leetcode.com/problems/intersection-of-two-linked-lists/ * O(n)空间解法 */ public ListNode GetIntersectionNode(ListNode headA, ListNode headB) { HashSet <ListNode> hashSet = new HashSet <ListNode>(); ListNode node = headA; while (node != null) { hashSet.Add(node); node = node.next; } node = headB; while (node != null && !hashSet.Contains(node)) { node = node.next; } return(node); }
public static ListNode ConstructLinkedList(int[] array) { if (array == null || array.Length == 0) { return(null); } var prev = new ListNode(-1); var head = new ListNode(array[0]); prev.next = head; for (int i = 1; i < array.Length; i++) { head.next = new ListNode(array[i]); head = head.next; } return(prev.next); }
public T RemoveLast() { if (Count == 0) { throw new System.ArgumentException("List is empty"); } ListNode <T> removedNode = tail; if (Count == 1) { head = tail = null; } else { tail = tail.PrevNode; tail.NextNode = null; } Count--; return(removedNode.Value); }
public static ListNode ToListNodeWithCircle(this List <int> list, int index) { ListNode node = null; if (list.Count == 0) { return(node); } if (index > list.Count - 1) { Debug.LogError("Can't convert to a List with circle ! ! !"); return(null); } ListNode circleNode = null; List <ListNode> nodeList = new List <ListNode>(); for (int i = 0; i < list.Count; i++) { ListNode temp = new ListNode(list[i]); nodeList.Add(temp); if (i == index) { circleNode = temp; } } for (int i = 0; i < nodeList.Count - 1; i++) { nodeList[i].next = nodeList[i + 1]; } node = nodeList[0]; nodeList[nodeList.Count - 1].next = circleNode; return(node); }
public bool IsPalindrome(ListNode head) { if (head == null || head.next == null) { return(true); } var length = 0; ListNode temp = head; while (temp != null) { length++; temp = temp.next; } int tailPosition = length % 2 == 0 ? length / 2 : length / 2 + 1; ListNode secondList = null, firstListTail = null, current = head; int currentNode = 1; while (currentNode < tailPosition) { current = current.next; currentNode++; } firstListTail = current; secondList = current.next; firstListTail.next = null; var secondHalfReversed = Reverse(secondList); bool isPalindrome = true; while (head != null && secondHalfReversed != null && isPalindrome) { isPalindrome = isPalindrome && head.val == secondHalfReversed.val; head = head.next; secondHalfReversed = secondHalfReversed.next; } return(isPalindrome); }
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null && l2 == null) { return(null); } ListNode preHead = new ListNode(-1); ListNode current = preHead; ListNode p1 = l1; ListNode p2 = l2; int carry = 0; while (p1 != null || p2 != null || carry > 0) { int value = 0; if (p1 != null) { value += p1.val; p1 = p1.next; } if (p2 != null) { value += p2.val; p2 = p2.next; } value += carry; carry = value / 10; value = value % 10; ListNode temp = new ListNode(value); current.next = temp; current = temp; } return(preHead.next); }
public void TestBase() { var head = new ListNode(1) { next = new ListNode(2) { next = new ListNode(3) { next = new ListNode(4) { next = new ListNode(5) } } } }; var expected = new ListNode(5) { next = new ListNode(4) { next = new ListNode(3) { next = new ListNode(2) { next = new ListNode(1) } } } }; var actual = sln.ReverseList(head); while (true) { if (expected == null) { return; } Assert.Equal(expected.val, actual.val); expected = expected.next; actual = actual.next; } }
public ListNode InsertionSortList(ListNode head) { if (head == null || head.next == null) { return(head); } ListNode oCur = head.next; ListNode oPrev = head; while (oCur != null) { if (oCur.val < oPrev.val) { ListNode iCur = head; ListNode iPrev = null; while (iCur != oCur && iCur.val < oCur.val) { iPrev = iCur; iCur = iCur.next; } ListNode temp = oCur.next; oPrev.next = temp; if (iPrev != null) { iPrev.next = oCur; } else { head = oCur; } oCur.next = iCur; oCur = temp; } else { oPrev = oCur; oCur = oCur.next; } } return(head); }
/// <summary> /// https://leetcode.com/problems/merge-k-sorted-lists/discuss/10630/C-Using-MinHeap-(PriorityQueue)-Implemented-Using-SortedDictionary /// </summary> /// <param name="lists"></param> /// <returns></returns> public static ListNode MergeKLists(ListNode[] lists) { var heap = new MinHeap(); /// put all nodes into minimum heap first one time foreach (var node in lists) { if (node == null) { continue; } heap.Add(node.val, node); } ///and then build a linked list using the ascending order ListNode curr = null, newHead = null; while (heap.map.Count > 0) { var node = heap.PopMin(); if (node.next != null) { heap.Add(node.next.val, node.next); } if (curr == null) { curr = node; newHead = curr; } else { curr.next = node; curr = curr.next; } } return(newHead); }
/// <summary> /// 非递归 /// 归并排序 自顶向下 /// </summary> /// <param name="head"></param> /// <returns></returns> public ListNode SortList_V2(ListNode head) { if (head?.next == null) return head; var fast = head.next; var slow = head; while (fast?.next!=null && slow!=null) { fast = fast.next.next; slow = slow.next; } //断开链接 var next = slow.next; slow.next = null; var left = SortList_V2(head); var right = SortList_V2(next); //合并 var result = new ListNode(0); var temp = result; while (left!=null && right!=null) { if (left.val < right.val) { temp.next = left; left = left.next; } else { temp.next = right; right = right.next; } temp = temp.next; } temp.next = left ?? right; return result.next; }
public ListNode ReverseKGroup(ListNode head, int k) { head = new ListNode(0) { next = head }; ListNode last = head; while (last.next != null) { ListNode nextLast = last.next; for (int i = 1; i < k; i++) { ListNode current = last.next; ListNode next = current.next; ListNode target = current; int j = 0; while (j < k - i && target.next != null) { target = target.next; j++; } if (j != k - i) { break; } current.next = target.next; target.next = current; last.next = next; } last = nextLast; } return(head.next); }
public bool IsPalindrome(ListNode head) { var tmp = head; var len = 0; while (tmp != null) { ++len; tmp = tmp.next; } if (len <= 1) { return(true); } var i = 0; var secondHalfHeadIdx = len % 2 == 0 ? len / 2 : len / 2 + 1; ListNode secondHalf = head; while (i != secondHalfHeadIdx) { secondHalf = secondHalf.next; ++i; } secondHalf = Reverse(secondHalf); while (secondHalf != null) { if (head.val != secondHalf.val) { return(false); } head = head.next; secondHalf = secondHalf.next; } return(true); }
// Use this for initialization void Start() { ListNode l1 = new ListNode(2); ListNode l1_1 = new ListNode(4); ListNode l1_2 = new ListNode(3); l1.next = l1_1; l1_1.next = l1_2; ListNode l2 = new ListNode(5); ListNode l2_1 = new ListNode(6); ListNode l2_2 = new ListNode(4); l2.next = l2_1; l2_1.next = l2_2; AddTwoNumber(l1, l2); char c = '1'; int temp = c - '0'; int[][] arr = new int[1][]; }
public int[] NextLargerNodes(ListNode head) { var ret = new Dictionary <int, int>(); var stack = new Stack <(int Index, int Value)>(); int i; for (i = 0; head != null; head = head.next, ++i) { int val = head.val; while (stack.TryPeek(out var t) && t.Value < val) { ret[t.Index] = val; stack.Pop(); } stack.Push((Index: i, Value: val)); } return(Enumerable .Range(0, i) .Select(x => ret.TryGetValue(x, out int v) ? v : 0) .ToArray()); }