【发布时间】:2016-01-24 21:18:10
【问题描述】:
我对下面链表的 Java 实现中的最后一个“return”语句感到困惑。
代码如下:
//remove the node with duplicate data and return the linked list
static Node removeDuplicates(Node head) {
if(head == null)
return head;
Node temp = head;
while(null != temp.next) {
if(temp.data == temp.next.data)
temp.next = temp.next.next;
else
temp = temp.next;
}
return head;
}
最后一个“return”语句是“return head”,但不应该是“return temp”吗?我的解释是创建 temp 节点来复制头节点,并遍历整个链表。本次操作结束时,如果有重复数据,修改的是temp,所以最后一条语句应该是“return temp”。
上面我很困惑的代码实际上是正确的,谁能给我解释一下?
谢谢!
【问题讨论】:
标签: linked-list singly-linked-list