链表翻转。给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6

来源:互联网 发布:精通nginx 第二版 pdf 编辑:程序博客网 时间:2024/05/08 08:08

这道题是链表逆置的升级版。

#include<iostream>#include<assert.h>using namespace std;struct Node{    int _data;    Node* _next;    Node(const int& x)        : _data(x)        , _next(NULL)    {}};Node* Reverse(Node* head, Node* tail){    assert(head);    Node* cur = head;    Node* prev = NULL;    Node* next = NULL;    Node* ReversedHead;    if (head == NULL)        return NULL;    if (head->_next == NULL)        return head;    while (cur != tail)    {        next = cur->_next;        cur->_next = prev;        prev = cur;        cur = next;    }    ReversedHead = prev;    return ReversedHead;}Node* RotateList(Node* list, size_t k){    assert(list);    int count = 0;    int index = 0;    Node* cur = list->_next;    Node* head = list;    Node* tail = list;    Node* prev = list;    Node* RotataHead = NULL;    Node* RotataTail = NULL;    Node* RotataList = NULL;    for (int i = 0; i < k; ++i)    {        tail = tail->_next;        if (tail == NULL)            break;    }    RotataList = Reverse(head, tail);//翻转前k个节点    RotataTail = head;    head = tail;    while (tail)    {        tail = tail->_next;        index++;        if (head&&index%k == 0)        {            RotataHead = Reverse(head, tail);            RotataTail->_next = RotataHead;            RotataTail = head;            head = tail;        }    }    if (head)    {        RotataTail->_next = head;    }    return RotataList;}int main(){    Node* p1 = new Node(1);    Node* p2 = new Node(2);    Node* p3 = new Node(3);    Node* p4 = new Node(4);    Node* p5 = new Node(5);    Node* p6 = new Node(6);    p1->_next = p2;    p2->_next = p3;    p3->_next = p4;    p4->_next = p5;    p5->_next = p6;    //Node* p = RotateList(p1, 2);    Node* p = RotateList(p1, 5);    return 0;}
阅读全文
1 0
原创粉丝点击