chenxi16

导航

数据结构-1 02-线性结构3 Reversing Linked List

 

 1 #include<stdio.h>
 2 #define MAXN 100000
 3 struct node{
 4     int data,next;
 5     int nextr;
 6 };
 7 struct node a[MAXN];
 8 int n,k,start,startr;
 9 void read();
10 void reverse();
11 int main(){
12     read();
13     reverse();
14     return 0;
15 }
16 void read(){
17     int i;
18     int addr,data,next;
19     scanf("%d %d %d",&start,&n,&k);
20     for(i=0;i<n;i++){
21         scanf("%d %d %d",&addr,&data,&next);
22         a[addr].data = data;
23         a[addr].next = next;
24     }
25     i=1;
26     addr = a[start].next;
27     while(addr!=-1){
28         addr = a[addr].next;
29         i++;
30     }
31     n = i;
32 }
33 void reverse(){
34     int s[MAXN],i,j,count,addr,addrn;
35     s[0] = start;
36     j=1;
37     count = n/k;
38     while(j<=count){
39         for(i=0;i<k;i++){
40             if(j==1 && i==0){
41                 addrn = start;
42             }
43             else{
44                 addr = addrn;
45                 addrn = a[addr].next;
46                 a[addrn].nextr = addr;
47             }
48         }
49         s[j] = addrn;
50         j++;
51     }
52     
53     //输出
54    for(i=1;i<=count;i++){
55        addr = s[i];
56        for(j=1;j<=k;j++){
57            if(j!=k){
58                printf("%05d %d ",addr,a[addr].data);
59                if(a[addr].nextr!=-1)
60                printf("%05d\n",a[addr].nextr);
61                else printf("-1\n");
62                addr = a[addr].nextr;
63            }
64            else if(j==k){
65                printf("%05d %d ",addr,a[addr].data);
66            }
67        }
68        if(i!=count) printf("%05d\n",s[i+1]);
69    }
70    addr = a[s[count]].next;
71    if(addr==-1) printf("-1\n");
72    else{
73        printf("%05d\n",addr);
74        while(addr!=-1){
75           printf("%05d %d ",addr,a[addr].data);
76           if(a[addr].next!=-1)
77              printf("%05d\n",a[addr].next);
78           else printf("-1\n");
79            addr = a[addr].next;
80        }
81    }
82 }

注意:1.实现方法;2.格式输出,特别是输出-1的时候。

 

posted on 2020-03-31 23:18  chenxi16  阅读(99)  评论(0编辑  收藏  举报