熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> 數據結構 >> 正文

有個二級單鏈表,其中每個元素都含有一個指向一個單鏈表的指針。寫程序把這個二級鏈表展開稱一級單鏈表

2022-06-13   來源: 數據結構 

這個二級單鏈表只包括一些head
public class Link
{
public Link Next;
public int Data;
public Link(Link next int data)
{
thisNext = next;
thisData = data;
}
}
public class CascadeLink
{
public Link Next;
public CascadeLink NextHead;
public CascadeLink(CascadeLink nextHead Link next)
{
thisNext = next;
thisNextHead = nextHead;
}
}

下面做一個二級單鏈表GenerateLink和GenerateLink方法在前面都已經介紹過了
public static CascadeLink GenerateCascadeLink()
{
Link head = GenerateLink();
Link head = GenerateLink();
Link head = GenerateLink();
CascadeLink element = new CascadeLink(null head);
CascadeLink element = new CascadeLink(element head);
CascadeLink element = new CascadeLink(element head);
CascadeLink head = new CascadeLink(element null);
return head;
}
就是說這些單鏈表的表頭headheadheadhead……它們組成了一個二級單鏈表headnull –> head –> head –> head –> head
–>

我們的算法思想是 進行兩次遍歷在外層用curr遍歷二級單鏈表head在內層用curr遍歷每個單鏈表
public static Link GenerateNewLink(CascadeLink head)
{
CascadeLink curr = headNextHead;
Link newHead = currNext;
Link curr = newHead;
while (curr != null)
{
currNext = currNextNext;
while (currNext != null)
{
curr = currNext;
}
curr = currNextHead;
}
return newHead;
}

其中currNext = currNextNext; 這句話是關鍵它負責把上一個單鏈表的表尾和下一個單鏈表的非空表頭連接起來


From:http://tw.wingwit.com/Article/program/sjjg/201405/30938.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.