因为链表本身有序,所以可以从第二个结点看到最后一个结点,如果这个结点和前一个结点相同,就删掉这个结点。
因为给出的链表是单链表,所以前一个结点需要我们自己记录一下。
c++
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
// write code here
if(head == NULL){return head;}
ListNode* now = head->next;
ListNode* pre = head;
ListNode* next = NULL;
while(now!=NULL)
{
next = now->next;
if(now->val == pre->val)//相等,删除这个结点。注意这时pre不用更新。
{
pre->next = next;
delete now;
now = next;
}
else{
pre = now;
now = next;
}
}
return head;
}
};
java
import java.util.*;
public class Solution {
public ListNode deleteDuplicates (ListNode head) {
if(head == null){return head;}
ListNode now = head.next;
ListNode pre = head;
ListNode next = null;
while(now!=null)
{
next = now.next;
if(now.val == pre.val)//相等,删除这个结点。注意这时pre不用更新。
{
pre.next = next;
now = next;
}
else{
pre = now;
now = next;
}
}
return head;
}
}python
class Solution:
def deleteDuplicates(self , head ):
# write code here
if head == None:
return head
now = head.next
pre = head
Next = None
while now!=None:
Next = now.next
if now.val == pre.val:
#相等,删除这个结点。注意这时pre不用更新。
pre.next = Next
now = Next
else:
pre = now
now = Next
return head;
京公网安备 11010502036488号