1074 Reversing Linked List (25point(s)) - C语言 PAT 甲级

1074 Reversing Linked List (25point(s))

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤105) which is the total number of nodes, and a positive K (≤N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

Sample Output:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

题目大意:

1025 反转链表 (25point(s))

设计思路:

1025 反转链表(C语言)

  1. 利用数组存储节点
  2. 利用初始地址及 next 地址,为列表排序,并以 -1 为终点,记录真实节点数目
  3. 根据 k 值,反转链表,利用数组下标,对称交换即可
  • 最初想用链表的 next 地址值尾插反转链表,突然想到,此地址值并不是真的内存地址(卒~)
编译器:C (gcc)
#include <stdio.h>

typedef struct link{
    int addr;
    int data;
    int next;
}link;

int inputlink(int n, link links[]);
int sortlink(int n, int a, link links[]);
int reverselink(int n, int k, link links[]);
int printlink(int n, link links[]);

int main()
{
    int a, n, k;
    link links[100000] = {0};

    scanf("%d %d %d", &a, &n, &k);
    inputlink(n, links);

    n = sortlink(n, a, links);
    reverselink(n, k, links);

    printlink(n, links);

    return 0;
}

int reverselink(int n, int k, link links[])
{
    int i, j;
    link temp;
    for(i = 0; i < n / k; i++){
        for(j = i * k; j < i * k + k / 2; j++){
            temp = links[j];
            links[j] = links[i * k + (i+1) * k  - j - 1];
            links[i * k + (i+1) * k  - j - 1] = temp;
        }
    }
    return 0;
}

int printlink(int n, link links[])
{
    int i;
    for(i = 0; i < n - 1; i++)
        printf("%05d %d %05d\n", links[i].addr, links[i].data, links[i + 1].addr);
    printf("%05d %d -1\n", links[n - 1].addr, links[n - 1].data);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章