public void InsertIntoSortedList(ref ListNode headNode, int value) { if (headNode == null) { headNode = new ListNode(value); return; } ListNode newNode = new ListNode(value); if (value < headNode.Value) { newNode.Next = headNode; headNode = newNode; return; } ListNode curr = headNode; while (curr.Next != null) { if (value < curr.Next.Value) { newNode.Next = curr.Next; curr.Next = newNode; return; } curr = curr.Next; } curr.Next = newNode; }
public void Insert(int value) { if (mHead == null) { mHead = new ListNode(value); return; } ListNode newNode = new ListNode(value); ListNode curr = mHead; while (curr.Next != null) { curr = curr.Next; } curr.Next = newNode; }
public ListNode GetIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return(null); } ListNode a = headA; ListNode b = headB; //if a & b have different len, then we will stop the loop after second iteration while (a != b) { //for the end of first iteration, we just reset the pointer to the head of another linkedlist a = a == null ? headB : a.next; b = b == null ? headA : b.next; } return(a); }
public ListNode SwapPairs(ListNode head) { ListNode dummyHead = new ListNode(0); dummyHead.next = head; ListNode prev = dummyHead; ListNode curr = head; while (curr != null && curr.next != null) { ListNode next = curr.next; ListNode nextnext = next.next; prev.next = next; next.next = curr; curr.next = nextnext; prev = curr; curr = curr.next; } return(dummyHead.next); }
public void Delete(int value) { if (mHead == null) return; ListNode curr = mHead; ListNode prev = null; while (curr != null) { if (curr.Value == value) { if (curr == mHead) mHead = mHead.Next; else prev.Next = curr.Next; return; } prev = curr; curr = curr.Next; } }
private ListNode Do(ListNode head) { if (head == null) { return(null); } ListNode slow = head; ListNode fast = head; while (fast != null) { if (slow.val != fast.val) { slow.next = fast; slow = fast; } fast = fast.next; } slow.next = null; return(head); }
public void Clear() { mHead = null; }
public ListNode(int val, ListNode next) { mValue = val; mNext = next; }
public ListNode(int val) { mValue = val; mNext = null; }
public ListNode() { mValue = 0; mNext = null; }
public LinkedList() { mHead = null; }
public void Sort() { if (mHead == null || mHead.Next == null) return; ListNode newHead = null; ListNode curr = mHead; while (curr != null) { InsertIntoSortedList(ref newHead, curr.Value); curr = curr.Next; } mHead = newHead; }
public void Reverse() { if (mHead == null || mHead.Next == null) return; ListNode prev = null; ListNode tmp = null; while(mHead != null) { tmp = mHead.Next; mHead.Next = prev; prev = mHead; mHead = tmp; } mHead = prev; }