反转链表

给定一个常数K以及一个单链表L,请编写程序将L中每K个结点反转。例如:给定L为1→2→3→4→5→6,K为3,则输出应该为3→2→1→6→5→4;如果K为4,则输出应该为4→3→2→1→5→6,即最后不到K个元素不反转。
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址、结点总个数正整数N(<= 105)、以及正整数K(<=N),即要求反转的子链结点的个数。结点的地址是5位非负整数,NULL地址用-1表示
输入例子:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
输出例子:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

#include <iostream>
#include <iomanip>    //setfill setw需要
#include <vector>
using namespace std;

struct Node{             //定义链表结构体
    int address;
    int value;
    int nextAddress;
};

Node nodesCount[100000]; //必须声明在全局区,在栈中声明空间会不够
int main()
{
    int firstAdress, numberN, numberK;  //第一个节点的地址;节点总数;K数
    cin >> firstAdress >> numberN >> numberK;

    vector<Node> nodeList;

    Node tempNode;
    for(int i = 0; i < numberN; ++i)
    {
        cin >> tempNode.address >> tempNode.value >> tempNode.nextAddress;
        nodesCount[tempNode.address] = tempNode;
    }

    while(firstAdress != -1)                        //将节点按地址依次移入nodelist
    {
        nodeList.push_back(nodesCount[firstAdress]);
        firstAdress = nodesCount[firstAdress].nextAddress;
    }

    int ListSize = nodeList.size();   //计算链表长度
    int times = ListSize/numberK;             //计算翻转次数
    for(int i = 0; i < times; i++)
    {
        int startIndex = i*numberK;           //交换的起点
        int endIndex = startIndex + numberK - 1;   //交换的终点
        for(int j = 0; j < (numberK/2); j++)          //交换节点的位置
        {
//          int startIndex = i * numberK + j;
//          int endIndex = (i+1) * numberK - 1 - j; 
            tempNode = nodeList[startIndex+j]; 
            nodeList[startIndex+j] = nodeList[endIndex-j];
            nodeList[endIndex-j] = tempNode;
        }
    }

    for(int i = 0; i < ListSize-1; i++)       //改变节点的nextAddress
    {
        nodeList[i].nextAddress = nodeList[i+1].address;
        //  printf("%05d %d %05d\n",nodeList[i].address,nodeList[i].value,nodeList[i].nextAddress);
        cout << setfill('0') << setw(5) << nodeList[i].address <<" " << nodeList[i].value << " " 
            << setfill('0') << setw(5) << nodeList[i].nextAddress << endl;
    }
    nodeList[ListSize-1].nextAddress = -1;   //最后节点的nextAddress为-1
    cout << setfill('0') << setw(5) << nodeList[ListSize-1].address <<" " << nodeList[ListSize-1].value << " " 
        << nodeList[ListSize-1].nextAddress << endl;
//  printf("%05d %d %d\n",nodeList[ListSize-1].address,nodeList[ListSize-1].value,nodeList[ListSize-1].nextAddress);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值