LeetCode 第82题 直接上代码
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode nextNode = head;
if(null == head) {
return head;
}
ListNode tempNode = head.next;
if(null == tempNode) {
return head;
}
boolean flag = false;
while(tempNode != null && nextNode.val == tempNode.val) {
tempNode = tempNode.next;
flag = true;
}
nextNode.next = tempNode;
boolean count = false;
while(tempNode != null && tempNode.next != null) {
if(tempNode.val == tempNode.next.val) {
tempNode = tempNode.next;
count = true;
}else {
if(count) {
nextNode.next = tempNode.next;
tempNode = tempNode.next;
count = false;
}else {
nextNode = tempNode;
tempNode = tempNode.next;
}
}
}
if(count) {
nextNode.next = tempNode.next;
tempNode = tempNode.next;
}
if(flag) {
return head.next;
}
return head;
}
}
这个一开始想用两个指针指向遍历的节点,后来发现越写越复杂,感觉不对。改成了只用一个指针指向遍历的节点 只遍历了一次链表
|