链表的部分反转

链表的部分反转

题目要求:

给定一个链表,翻转该链表从m到n的位置。
要求直接翻转而非申请新空间
如:给定1→5→7→4→6→3→8→5,m=2,n=4,返回
1→4→7→5→6→3→8→5
假定给出的参数满足:1≤m≤n≤链表长度。

算法核心思想

pNext = pCur->pNext;
pCur->pNext = pHead->pNext;
pHead->pNext = pCur;
pre->pNext = pNext;
pCur = pNext;
这里写图片描述

代码段

代码块语法遵循标准C/C++代码

/*
* 问题描述:链表的部分反转
* C/C++ 语言
*
* @author Erice_s
* binbin_Erices@163.com
* @date 2017/11/9
*
*/
#include<iostream>
#include<time.h>

using namespace std;

typedef struct tagSNode
{
    int value;
    tagSNode *pNext;
    tagSNode(int v) :value(v), pNext(NULL){}
}SNode;

void Print(SNode*p)
{
    if (p == NULL)
    {
        cout << "Print failure:(p==NULL)\n";
        return;
    }
    p = p->pNext;
    while (p)
    {
        cout << p->value << " ";
        p = p->pNext;
    }
}

void Destroy(SNode*p)
{
    SNode *next;
    while (p)
    {
        next = p->pNext;
        delete p;
        p = next;
    }
}

int *Reserve(SNode *pHead, int from, int to)
{
    SNode *pCur = pHead->pNext;
    int i;
    for (i = 0; i < from - 1; i++)
    {
        pHead = pCur;
        pCur = pCur->pNext;
    }
    SNode *pre = pCur;
    pCur = pCur->pNext;
    to--;
    SNode *pNext;
    for (; i < to; i++)
    {
        pNext = pCur->pNext;
        pCur->pNext = pHead->pNext;
        pHead->pNext = pCur;
        pre->pNext = pNext;
        pCur = pNext;
    }

    return 0;
}


int main(void)
{
    SNode *pHead = new SNode(0);
    int i;
    time_t ts;
    srand((unsigned int)time(&ts));
    for (i = 0; i < 10; i++)
    {
        SNode *p = new SNode(rand() % 10);
        p->pNext = pHead->pNext;
        pHead->pNext = p;
    }
    Print(pHead);

    Reserve(pHead, 3, 6);

    cout << endl;
    Print(pHead);
    Destroy(pHead);

    system("pause");
    return 0;
}

实验结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Erice_s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值