Re: [問題] 把兩個linkedlist合併成一個
※ 引述《helenus (就是愛SEX)》之銘言:
: 就是建立兩個linked-list 然後可以讓人用鍵盤輸入數字
: 比如說第一個linked-list輸入 1 4 7三個數字
: 第二個linked-list輸入 2 5 6三個數字
: 接著螢幕上會顯示出合併後的數字1 2 4 5 6 7
: 並且把最大的數值7也顯示出來
: (底下是我寫的code 如果有改進的地方也請大家跟我說 謝謝)
恕刪
: (我想問一下 寫到這裡我應該怎麼把兩個linkedlist合併成一個
: 由小到大的串列呢?)
: }
: }
要不要考慮再創一個linkedlist
然後用while的方式將兩個list的資料寫入?
意思大概是這樣(變數稍微跟你的不一樣)
用的方法跟你print data的while迴圈差不多
=========================================
//怕以後可能還想使用List1跟List2的參考
//所以乾脆先各複製一份參考to combine裡面的data
//以下寫在main void裡
List1_tc = List1;
List2_tc = List2;
LinkedList MainList = new LinkedList();
//如果要玩很多LinkedList合併
//可以宣告LinkedList TempList[] = new LinkedList();
//然後下面再多個for迴圈在外面
while(List1_tc.nextNode != null)
{
int tempvalue = List1.data;
List1 = List1.nextNode;
MainList.insert(tempvalue);
//後面fasle我就不打了,基本上Node本身應該要能判斷
//不要從外面決定true or fasle,如果沒有資料你可以用insert at front
//再設定剛開始的firstNode跟LastNode指向同參考
}
然後List2_tc一樣
最後
System.out.print("Mainlist串列 : ");
MainList.print();
System.out.println("最大數字為 : " + MainList.data);
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.167.82.114
※ 編輯: Egriawei 來自: 218.167.82.114 (05/07 23:20)
討論串 (同標題文章)
java 近期熱門文章
PTT數位生活區 即時熱門文章