题目:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:
1.用递归删除,遇到相同的往后走,返回第一个不相同的节点
2.循环删除,定义一个新节点,指向phead,定义pre指向新节点,cur指向phead,移动cur,遇到不相等,移动pre
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead==null)
return null;
if(pHead!=null && pHead.next==null)
return pHead;
ListNode current;
if(pHead.val==pHead.next.val){
current=pHead.next.next;
while (current != null && current.val==pHead.val)
current=current.next;
return deleteDuplication(current);//继续删除后面的重复节点
}else{
current=pHead.next;
pHead.next=deleteDuplication(current);//这里返回的就是第一个不相同的节点
return pHead;
}
}
}
思路2,C++版
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
if(!pHead || !pHead->next)return pHead;
ListNode* newhead = new ListNode(-1);
newhead->next=pHead;
ListNode* pre=newhead, *cur=pHead;
while(cur){
if(cur->next && cur->val==cur->next->val){
while(cur->next && cur->val==cur->next->val){
cur=cur->next;
}
cur=cur->next;
pre->next=cur;
}else{
pre=cur;
cur=cur->next;
}
}
return newhead->next;
}
};