Leetcode linklist Special Topic

Source: Internet
Author: User

This blog will be leetcode on the linklist topic content here, followed by slowly add

One: Leetcode 206 Reverse Linked list two: Leetcode Reverse Linked List II

A: Leetcode 206 Reverse Linked List

Topic:

Reverse a singly linked list.

Code:

Class Solution {public:    listnode* reverselist (listnode* head) {        if (head = = NULL) return null;        ListNode *p = head;        ListNode *pnext = p->next;        P->next = NULL;       The head node needs to point to NULL otherwise time limit while        (pnext! = NULL) {            ListNode *q = pnext->next;            Pnext->next = p;            p = pnext;   Iteration            pnext = q;        }        return p;            }};
II: Leetcode Reverse Linked List II

Topic:

Reverse a linked list from position m to N. Do it in-place and in One-pass.

For example:
Given 1->2->3->4->5->NULL , m = 2 and n = 4,

Return 1->4->3->2->5->NULL .

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤length of list.

Analysis: This problem is slightly more complicated than a little, but it is also easy to solve

Code:

Class Solution {public:    listnode* Reversebetween (listnode* head, int m, int n) {        if (m = = N) return head;        ListNode *pre = head;        ListNode *p = head;        for (int i = 1; i < m; i++) {    //Find the first M element and its previous element            pre = p;            p = p->next;        }        ListNode *curr = p;        ListNode *pnext = p->next;   Invert the elements that need to be reverse in the middle to take advantage of the idea in reverse linked list for        (int i = m; i < n; i++) {            ListNode *q = pnext->next;< C14/>pnext->next = p;            p = pnext;            Pnext = q;        }        Curr->next = Pnext;        if (pre! = curr) Pre->next = p;      Inequality indicates m!=1  then Pre->next = p, and equality indicates m==1, then head ==p        else head = p;        return head;            };



Leetcode linklist Special Topic

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.