【发布时间】:2015-09-30 00:35:22
【问题描述】:
问题陈述: 您将获得指向两个链表的头节点的指针,这些链表在某个节点处合并在一起。找到发生这种合并的节点。两个头节点将不同,并且都不会为 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;
【问题讨论】:
-
Node* 不是 java 语法,可能是 C 或 C++ 程序?如果是这样,请更改标签
标签: java data-structures merge linked-list nodes