問題描述: 給出指向兩個鏈接列表的頭節點的指針,這兩個鏈接列表在某個節點上合併在一起。找到發生此合併的節點。兩個頭節點將會不同,都不會爲NULL。通過顛倒列表查找兩個列表的合併點
輸入格式 您必須完成int FindMergeNode(Node * headA,Node * headB)方法,該方法接受兩個參數 - 鏈接列表的頭部。你不應該讀取標準輸入/控制檯的任何輸入。
輸出格式 查找兩個列表合併並返回該節點的數據的節點。不要將任何東西打印到標準輸出/控制檯。
我想扭轉這兩個列表,然後分別走過他們每個人,直到我到達最後一個公共節點。但是在測試時,它沒有給出正確的輸出。 我的想法是錯的還是我的代碼錯了?這是一個好方法還是壞方法?
我的代碼:
int FindMergeNode(Node headA, Node headB) {
//Reverse listA
Node currentA = headA;
Node prevA = null;
Node NextA;
while(currentA!=null){
NextA = currentA.next;
currentA.next = prevA;
prevA = currentA;
currentA = NextA;
}
headA = prevA;
//Reverse listB
Node currentB = headB;
Node prevB = null;
Node NextB;
while(currentB!=null){
NextB = currentB.next;
currentB.next = prevB;
prevB = currentB;
currentB = NextB;
}
headB = prevB;
//Iterate throught the reversed list and find the last common node.
Node n = headA;
Node m = headB;
while(n.next!=m.next){
n = n.next;
m = m.next;
}
return n.data;
}
鏈接問題:https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists
編輯:從KARTHIK的回答,我修改了第三while循環,但它畢竟是給了錯誤的輸出。
//Iterate throught the reversed list and find the last common node.
Node n = headA;
Node m = headB;
while(n.next == m.next){
n = n.next;
m = m.next;
}
return n.data;
節點*是不是Java的語法,可能是它是一個C或C++程序?如果是這樣,更改標籤 –