菜鸟笔记
提升您的技术认知

[c ]链表部分翻转-ag真人游戏

// partreverse.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include 
#include 
using std::cout;
using std::endl;
typedef struct snode {
    int value;
    snode *pnext;
    snode(int v):value(v),pnext(null){}
}snode;
void print(snode* head) {
    snode* p = head->pnext;
    while (p) {
        cout << p->value;
        p = p->pnext;
        if (p)
            cout << "->";
    }
    cout << endl;
}
void destroy(snode* head) {
    while (head)
    {
        snode* p = head;
        head = head->pnext;
        delete p;
    }
}
void partreverse(snode *head, int m, int n) {
    snode* p = head;
    snode* pnext = null;
    int i = 1;
    //找到第m个数的前驱
    while (i < m) {
        p = p->pnext;
        i  ;
    }
    //移动结点
    i = 0;
    //记录被交换的第一个结点
    snode* initnext = p->pnext;
    //pnext指向被交换的第二结点
    pnext = p->pnext->pnext;
    while (ipnext;
        //头插法
        pcur->pnext = p->pnext;
        p->pnext = pcur;
        i  ;
    }
    //pnext指向被移动最后一个结点的下一结点
    initnext->pnext = pnext;
}
int main()
{
    snode* head = new snode(0);
    for (int i = 0; i < 13; i  ) {
        snode* p = new snode(rand() % 10);
        p->pnext = head->pnext;
        head->pnext = p;
    }
    cout << "before:\t";
    print(head);
    partreverse(head, 6, 9);
    cout << "after:\t";
    print(head);
    destroy(head);
    system("pause");
    return 0;
}
网站地图