Algorithm summary-linked list

Source: Internet
Author: User
Tags prev

The problem of the linked list is not high, but the actual writing process needs to pay attention to the language details, a lot of places to consider the fineness.

1. Linked list structure and basic operation

1.1 Adding nodes

General situation:

Cur->next = prev->next;prev->next = cur;

Table Header Insert:

Cur->next = Head;head = cur;

1.2 Deleting a node

General: (known as the predecessor node of the node to be deleted)

listnode* temp = Prev->next;prev->next = Prev->next->next;delete temp;

Table header Element Deletion:

listnode* temp = head->next;delete Head;head = temp;

Deformation topic: (Known to delete the node, and do not know the position of the head pointer, leetcode237 https://leetcode.com/problems/delete-node-in-a-linked-list/)

Idea: Copy the contents of the successor node of the node to be deleted to the current node, and then delete the subsequent node, which is the equivalent of subsequent deletion of the current node.

Class Solution {public:    void Deletenode (listnode* node) {        Node->val = node->next->val;        listnode* temp = node->next;        Node->next = node->next->next;        Delete temp;}    ;

Note the special handling of boundary conditions when adding or deleting.

2. Summary of common types of questions

2.1Remove duplicates from Sorted List 1 (leetcode83 https://leetcode.com/problems/remove-duplicates-from-sorted-list/ )

Remove duplicates from Sorted List 2 (leetcode82 https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ )

Ideas: 1 Direct thinking, that is, traversing the list, found the same element is deleted, or continue to the next step

Class Solution {public:    listnode* deleteduplicates (listnode* head) {        if (head = = NULL) {            return head;        }        listnode* dummy = new ListNode (0);        Dummy->next = head;        while (head->next! = NULL) {            if (head->next->val = = head->val) {                listnode* temp = head->next;                Head->next = head->next->next;                Delete temp;            }            else{                head = head->next;            }        }        Return dummy->next;    }};

2. Because it involves deleting all duplicate elements, the deletion process needs to get the precursor node of the element to be deleted, so the Head->next and head->next->next are used to ensure that the deletion work can be realized.

Class Solution {public:    listnode* deleteduplicates (listnode* head) {    if (head = = NULL) {        return head;    }    listnode* dummy = new ListNode (0);    Dummy->next = head;    head = dummy;    while (head->next! = null&& Head->next->next! = NULL) {        if (Head->next->val = = head->next- >next->val) {            int val = head->next->val;            while (head->next! = NULL && Head->next->val = = val) {                listnode* Curr = head->next;                Head->next = head->next->next;                Delete Curr;            }        }        else{            head = head->next;        }    }    Return dummy->next;    }};

2.2 Linked list Rollover related topics

2.2.1 Chain list Overall rollover (Leetcode 206 https://leetcode.com/problems/reverse-linked-list/)

Idea: traverse the linked list, and use the current node as a new header (head interpolation) that has been flipped to a successful list

Class Solution {public:    listnode* reverselist (listnode* head) {        listnode* result = NULL;        while (head) {            listnode* temp = head->next;            Head->next = result;            result = head;            Head = temp;        }        return result;}    ;

2.2.2 List part rollover (Leetcode https://leetcode.com/problems/reverse-linked-list-ii/)

Idea: Link list as three parts, namely head to M,m to N,n to last.

After flipping the m,n, reconnect the linked list, paying attention to the case where M is 1 o'clock (using dummy node, unified processing)

Class Solution {public:    listnode* Reversebetween (listnode* head, int m, int n) {        ListNode *dummy = new ListNode (0) ;        Dummy->next = head;        head = dummy;        for (int i = 0;i < m-1;i++) {            head = head->next;        }        listnode* Temp1 = head;        Head = head->next;        listnode* temp2 = head;        listnode* result = NULL;        for (int i = M;i <= n; i++) {            listnode* temp = head->next;            Head->next = result;            result = head;            Head = temp;        }        Temp1->next = result;        Temp2->next = head;        Return dummy->next;    }};

2.2.3 Chain list palindrome judgment (Leetcode 234 https://leetcode.com/problems/palindrome-linked-list/)

Ideas: Find the midpoint of the list (see the following two pointers), the latter part of the flip, compared with the first half, get whether palindrome.

Class Solution {public:    bool Ispalindrome (listnode* head) {        if (head = = NULL | | Head->next = = NULL) {            return true;        }        listnode* fast = head;        listnode* slow = head;        while (Fast->next = null &&  Fast->next->next! = null) {            slow = slow->next;            Fast = fast->next->next;        }   listnode* mid = slow;        slow = slow->next;        listnode* result = NULL;        while (slow! = NULL) {            listnode* temp = slow->next;            Slow->next = result;            result = slow;            slow = temp;        }        Mid->next = NULL;        while (result = NULL) {            if (head->val! = result->val) {                return false;            }            Head = head->next;            result = result->next;        }        return true;            }};

2.3-Pointers Thinking application

2.3.1 Find the midpoint of a list or a particular point position (Leetcode https://leetcode.com/problems/remove-nth-node-from-end-of-list/)

Idea: The quick pointer walks two steps at a time, the slow pointer goes one step at a time, the fast pointer reaches the end of the list, and the slow pointer points to the midpoint.

listnode* Findmiddle (listnode* head) {        listnode* chaser = head;        listnode* runner = head->next;        while (runner = null && Runner->next! = null) {            chaser = chaser->next;            Runner = runner->next->next;        }        return chaser;    }

A pointer to go first n step, then the speed of the pointer together, the fast pointer reached the end, the slow pointer reached the node to be deleted.

Note: The deletion of the first element is often problematic, you can use dummy node to add Sentinel to the list, so that the list can be unified processing.

Class Solution {public:    listnode* removenthfromend (listnode* head, int n) {        if (head = = NULL) {            return head;< c3/>}        listnode* dummy = new ListNode (0);        Dummy->next = head;        head = dummy;        listnode* slow = head;        listnode* fast = head;        for (int i = 0; I <n; i++) {            fast = Fast->next;        }        while (fast->next! = NULL) {            fast = fast->next;            slow = slow->next;        }        listnode* temp = slow->next;        Slow->next = slow->next->next;        Delete temp;        Return dummy->next;    }};

2.3.2 given a single linked list, find the intersection of the two (Leetcode https://leetcode.com/problems/intersection-of-two-linked-lists/)

Idea: Calculate the length of the linked list, let the long list go the distance of the difference, and then traverse at the same time to find the same element

Class Solution {public:    int getlength (listnode* head) {        int num = 0;        while (head! = NULL) {            head = head->next;            num++;        }        return num;    }    ListNode *getintersectionnode (ListNode *heada, ListNode *headb) {        int lA = GetLength (Heada);        int LB = GetLength (headb);        if (LA >= LB) {for            (int i = 0; i < la-lb; i++) {                Heada = heada->next;            }        }        else{for            (int i = 0;i < Lb-la; i++) {                headb = headb->next;            }        }        while (Heada = null && HEADB! = null) {            if (Heada = = headb) {                return heada;            }            Heada = heada->next;            HEADB = headb->next;        }        return NULL;    }};

2.3.3 determine if a single linked list has a ring

(Leetcode 141 142 https://leetcode.com/problems/linked-list-cycle/https://leetcode.com/problems/linked-list-cycle-ii/)

Ideas: 1) pointers a fast and slow, there are rings, the inevitable encounter.

Class Solution {public:    bool Hascycle (ListNode *head) {        if (head = = NULL) {            return 0;        }        listnode* slow = head;        listnode* fast = head;        while (fast!= NULL && fast->next! = null) {            slow = slow->next;            Fast = fast->next->next;            if (slow = = fast) {                return 1;            }        }        return 0;}    };

2)

2 (A + b) = a + b +n (b + C)

Launch a = (n-1) B + NC i.e. A = (n-1) (b+c) + C

Because the b+c is the length of the ring, so say two pointers, respectively, refers to the link head and the initial encounter position, they will also meet at the beginning of the ring, so to organize the idea

① with the first question, the fast and slow pointer to determine if there is a ring, and record the location of the meeting

② the two pointers are placed at the beginning and the meeting position, the same speed is pushed, then according to the derivation should meet at the beginning of the ring

Class Solution {public:    listnode *detectcycle (ListNode *head) {        if (head = = NULL) {            return 0;        }        listnode* slow = head;        listnode* fast = head;        while (fast! = NULL && Fast->next! = null) {            slow = slow->next;            Fast = fast->next->next;            if (slow = = fast) {break                ;            }        }        if (fast = = NULL | | fast->next = = NULL) {            return null;        }        slow = head;        while (slow! = fast) {            slow = slow->next;            Fast = fast->next;        }        return slow;}    ;

Cond

Algorithm summary-linked list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.