实现链表中的部分翻转

思路是,保存四个节点,翻转前后的节点,翻转中间的链表,记录头尾,然后连接。暂时没有考虑从0和末尾开始翻转。

#include <iostream>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL){}
};

ListNode* ReverseList1(ListNode* head, int m, int n)
{
    int length = n-m+1;
    ListNode* first = head;
    ListNode* pre = head;
    ListNode* end = head;
    
    int i = 0;
    while(i <= n)
    {
        if(i == m-1)
            pre = head;
        end = head;
        head = head->next;
        i++;
    }
    end = end->next;
    cout << pre->val << endl;
    cout << end->val << endl;

    ListNode * newlistend = pre->next;
    cout << newlistend->val << endl;
    head = pre->next;
    cout << head->val << endl;
    ListNode* newlist = NULL;
    while( head!= NULL && length)
    {
        ListNode* temp = head->next;
        head->next = newlist;
        newlist = head;
        head = temp;
        length--;
    }

    for(ListNode *t = newlist; t != NULL; t = t->next)
    {
        cout << t->val ;
    }
    cout << endl;

    pre->next = newlist;
    newlistend->next = end;
    return first;
}

int main()
{
    ListNode a(0);
    ListNode b(1);
    ListNode c(2);
    ListNode d(3);
    ListNode f(4);
    ListNode e(5);
    ListNode g(6);
    a.next = &b;
    b.next = &c;
    c.next = &d;
    d.next = &f;
    f.next = &e;
    e.next = &g;
    for(ListNode *t = &a; t != NULL; t = t->next)
    {
        cout << t->val ;
    }
    cout << endl;
    ReverseList1(&a, 0, 4);
    for(ListNode *t = &a; t != NULL; t = t->next)
    {
        cout << t->val;
    }
    return 0;
}

 

posted @ 2021-01-14 11:04  11YS  阅读(140)  评论(0编辑  收藏  举报