zoukankan      html  css  js  c++  java
  • 1074 Reversing Linked List

    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 (≤) which is the total number of nodes, and a positive K (≤) 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

    题意:

      给出一个用数字表示指针的链表,将链表中的每k个数字进行反转。

    思路:

      本来想的是用结构体来存储,可是提交的时候,有一个测试点超时,还有一个测试点没有的通过。

      date[address]表示链表所在结点中的值,next[address]表示链表所指向的下一个结点,list[]用来存储排序好的数组。有一点需要注意就是并不是所有的结点都会出现在结果中。有一个地方挺巧妙的,就是再进行反转的时候下标的确定方法:i / k * k + k - 1 - (i % k).

    Code:

     1 #include <bits/stdc++.h>
     2 
     3 using namespace std;
     4 
     5 int main() {
     6     int start, n, k;
     7     cin >> start >> n >> k;
     8     int address, val, next;
     9     int date[100005], nextNode[100005], list[100005], ans[100005];
    10     for (int i = 0; i < n; ++i) {
    11         cin >> address;
    12         cin >> date[address] >> nextNode[address];
    13     }
    14     int first = start, index = 0;
    15     while (first != -1) {
    16         list[index++] = first;
    17         first = nextNode[first];
    18     }
    19     for (int i = 0; i < index; ++i) ans[i] = list[i];
    20     for (int i = 0; i < index - index % k; ++i)
    21         ans[i] = list[i / k * k + k - i % k - 1];
    22     for (int i = 0; i < index - 1; ++i) {
    23         printf("%05d %d %05d
    ", ans[i], date[ans[i]], ans[i + 1]);
    24     }
    25     printf("%05d %d -1
    ", ans[index - 1], date[ans[index - 1]]);
    26 
    27     return 0;
    28 }
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    关于Winsock编程中IO重叠的概念
    comparator接口与Comparable接口的区别
    String、StringBuffer与StringBuilder之间区别
    Oracle 中 call 和 exec的区别
    谈谈对Spring IOC的理解(转)
    常见的几种RuntimeException
    long(Long)与int(Integer)之间的转换
    ValueStack值栈和ActionContext
    Struts2执行过程解析
    Struts2的经典入门
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12819604.html
Copyright © 2011-2022 走看看