这道题还没AC,现在是21分,最后两个测试点过不了,看大家的讨论是一个超时问题效率太低,另外输入的结点有的无效,链表长度需要自己统计而不能直接用n。现在时间紧先赶进度,但以后一定要把这些细节问题弄明白呀。
1025. 反转链表 (25)
给定一个常数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是下一结点的地址。
输出格式:
对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。
输入样例: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<algorithm> #include<iomanip> #include<cstring> #include<vector> #include<stdio.h> #include<math.h> #include<string> #include<sstream> using namespace std; struct node{ int prev; int next; int value; }; bool operator == (const node& a, const node& b) { return a.prev == b.next; } bool cmp(node a,node b){ if(a.prev<b.prev)return true; else return false; } int main(){ int firstAdd,n,k; cin>>firstAdd>>n>>k; vector<node> vec; vector<node> v; vector<node> r; node *arr=new node[n]; memset(arr,0,sizeof(arr)); node *a=new node[n]; memset(arr,0,sizeof(a)); for(int i=0;i<n;i++){ node n; cin>>n.prev>>n.value>>n.next; vec.push_back(n); } sort(vec.begin(),vec.end(),cmp); node current; current.next=firstAdd; vector<node>::iterator it; int index=0; while(current.next!=-1){ it=find(vec.begin(),vec.end(),current); current=*it; arr[index].next=current.next; arr[index].prev=current.prev; arr[index].value=current.value; index++; } index=0; int sum=k-1; while(sum<n){ for(int i=0;i<k;i++){ a[index].prev=arr[sum-i].prev; a[index].value=arr[sum-i].value; index++; } sum+=k; } for(;index<n;index++) { a[index].prev=arr[index].prev; a[index].value=arr[index].value; } for(int i=0;i<n;i++) { a[i].next=a[i+1].prev; } for(int i=0;i<n-1;i++){ printf("%05d %d %05d\n",a[i].prev,a[i].value,a[i].next); } printf("%05d %d %d",a[n-1].prev,a[n-1].value,-1); return 0; }