Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
题目意思为删除链表中重复的元素
思路: 遍历链表,用两个指针,一个指向前一个,一个指向后一个,当两个所指向的值不相等时,同时往后移,当两个指向的值相等时,需要删除一个元素(后一个指针指向的值),然后后一个往后遍历
代码如下:
<span style="font-size:18px;">/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if(head==NULL||head->next==NULL) return head; ListNode *p,*q,*pur; p=head; q=p->next; while(q!=NULL) { if(p->val==q->val) { pur=q; q=q->next; p->next=q; delete pur; } else { p=q; q=q->next; } } return head; } };</span>
时间: 2024-10-03 16:11:58