题目描述:
给定一个常数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表示。 接下来有N行,每行格式为: Address Data Next 其中Address是结点地址,Data是该结点保存的整数数据,Next是下一结点的地址。
输出描述
对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。
我的代码结果正确,但超时了。。
#include <iostream>
#include <stack>
#include <vector>
#include <string>
using namespace std;
class linknode {
public:
string previous;
int data;
string next;
linknode(string previous, int data, string next)
{
this->data = data;
this->next = next;
this->previous = previous;
}
};
int main(void) {
vector<linknode> nodes_vector;
vector<linknode> nodes_temp_vector;
string next_node;
int n, k;
string previous, next;
int data;
int index=0;
cin>> next_node>>n>>k;
for (int i = 0; i < n; ++i) {
cin>> previous >>data>>next;
linknode node(previous, data, next);
nodes_vector.push_back(node);
}
while(next_node!="-1")
{
for (int i = 0; i < n; ++i)
{
linknode node = nodes_vector[i];
if (node.previous == next_node)
{
nodes_temp_vector.push_back(node);
next_node = node.next;
break;
}
}
}
nodes_vector.clear();
stack<linknode> nodes_stack;
for (int i = 0; i < (n / k); i++)
{
for (int j = 0; j < k; j++)
{
nodes_stack.push(nodes_temp_vector[index]);
index++;
}
for (int j = 0; j < k; j++)
{
nodes_vector.push_back(nodes_stack.top());
nodes_stack.pop();
}
}
for (int i = index; i < n; i++)
{
nodes_vector.push_back(nodes_temp_vector[i]);
}
for (int i = 0; i < n; i++)
{
cout << nodes_vector[i].previous <<" "<< nodes_vector[i].data <<" "
<<nodes_vector[i].next<< endl;
}
return 0;
}
贴一份牛客网上面的回答
链接:https://www.nowcoder.com/questionTerminal/5f44c42fd21a42b8aeb889ab83b17ad0
来源:牛客网
#include <stdio.h>
#include <memory.h>
#define LIMIT 100002
struct linknode {
int data;
int next;
};
int reversek(struct linknode *, int, int);
int main(void) {
struct linknode list[LIMIT];
int faddr, n, k;
int addr, data, next;
int i, j, count = 0;
scanf("%d %d %d", &faddr, &n, &k);
memset(list, 0, LIMIT * sizeof(struct linknode));
list[LIMIT-1].next = faddr; //head node
for(i = 0; i < n; ++i) {
scanf("%d %d %d", &addr, &data, &next);
list[addr].data = data;
list[addr].next = next;
}
for(i = list[LIMIT-1].next; i != -1; i = list[i].next)
++count; //count valid nodes
for(j = count / k, i = LIMIT - 1; j > 0 && i != -1; --j)
i = reversek(list, i, k); //reverse every k nodes
for(i = list[LIMIT-1].next; list[i].next != -1; i = list[i].next)
printf("%05d %d %05d\n", i, list[i].data, list[i].next);
printf("%05d %d %d\n", i, list[i].data, list[i].next);
return 0;
}
int reversek(struct linknode *list, int head, int k) {
int i, j, p;
int nexthead;
for(j = 0, p = list[head].next; j < k && p != -1; ++j) //find tail
p = list[p].next;
nexthead = list[head].next;
list[head].next = p;
for(j = 0, i = nexthead; j < k && i != -1; ++j) {
p = list[i].next;
list[i].next = list[head].next; //insert at the head
list[head].next = i;
i = p;
}
return nexthead;
}