MOOC 數據結構 | 2. 線性結構(6):習題選講---Reversing Linked List

題目

02-線性結構3 Reversing Linked List (25 分)

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 (≤10​5​​) 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

分析

什麼是抽象的鏈表

  • 有塊地方存數據
  • 有塊地方存指針 ---- 下一個結點的地址

樣例輸入可以模擬一個真實的鏈表在內存裏存在狀態,開一個結構數組來代表內存空間,樣例輸入中的位置就是在數組中的下標,指針其實就是一個整數,記錄的是下一個結點在數組中的下標。

根據地址關係可以得到下面的指向:

從頭結點開始,順着next指針,就可以遍歷這個鏈表,同時也建立起了一個單鏈表:

接下來的問題就是如何把這單鏈表逆序。

單鏈表的逆轉

逆轉後的鏈表形態:

如何實現呢?

new指針:新的已經逆轉的鏈表的頭結點

old指針:指向當前還沒有完成逆轉的老鏈表的頭結點

tmp指針:記錄老鏈表的頭結點的後一個結點,否則後面的沒有逆轉的鏈表就被丟掉了

一開始的時候三個指針的指向:

記住了3的位置後,就可以把2的指針反向使它指向1:

完成這步之後,指針向前位移,new指向當前逆轉鏈表的頭結點,old指向當前還沒有逆轉的鏈表的頭結點,tmp指向old的下一個結點:

重複上面的步驟:

以此類推,一直重複k步。

所以就需要一個計數器,需要逆序的結點達到k時,停下來,(上圖就是樣例中k = 4的時候),此時結點1的指向是不對的,應該指向結點5,即是當前還沒有逆轉的老的鏈表的頭結點:

空的頭結點應該指向4,即當前已經逆轉的鏈表的頭結點,也就是new指針所指的位置:

僞代碼:如果沒有K的限制,整個鏈表逆轉,那麼當old 爲空的時候,逆轉結束。

參數head默認指向的是空的頭結點,因爲有K的限制,所以:

測試數據

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章