Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
去除链表中的冗余项
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode *tmp=head;
while(tmp!=nullptr)
{
int c=tmp->val;
ListNode *tp=tmp->next;
while(tp!=nullptr&&tp->val==c)
tp=tp->next;
tmp->next=tp;
tmp=tmp->next;
}
return head;
}
};
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5 Output: 1->2->5
Example 2:
Input: 1->1->1->2->3 Output: 2->3
还是关于指针链表的相关操作。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode *rh=new ListNode(0),*tmp=rh;
rh->next=head;
while(tmp->next!=nullptr)
{
int c=tmp->next->val;
ListNode *tp=tmp->next;
if(tp->next!=nullptr&&tp->next->val==c)
{
while(tp!=nullptr&&tp->val==c)
tp=tp->next;
tmp->next=tp;
continue;
}
tmp=tmp->next;
}
return rh->next;
}
};
我这里的做法是给原来的链表添加了一个“头”rh,之后再进行while的循环逻辑就会非常通顺,代码也不难理解。