题目描述:
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null) {
return pHead;
}
ListNode pre = pHead;
ListNode cur = pHead;
int flag = 0;
if (pHead.next.val == pHead.val) {
flag = 1;
}
while (cur != null) {
if (cur.next == null)
break;
if (cur.next.val != cur.val) {
pre = cur;
cur = cur.next;
} else {
while (cur.next != null && cur.next.val == cur.val) {
cur = cur.next;
}
pre.next = cur.next;
cur = cur.next;
}
}
return flag == 1 ? pHead.next : pHead;
}
方法2:先将链表元素复制到ArrayList中去,并去除重复元素,最后初始化新的链表。
public ListNode deleteDuplication(ListNode pHead){
if (pHead == null || pHead.next == null) {
return pHead;
}
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> deleteList = new ArrayList<Integer>();
ListNode p = pHead;
while(p != null){
if(!list.contains(p.val) && !deleteList.contains(p.val)){
list.add(p.val);
}
else{
list.remove(new Integer(p.val));
deleteList.add(p.val);
}
p = p.next;
}
if(list.size() == 0){
return null;
}
pHead.val = list.get(0);
ListNode cur = pHead;
for(int i=1;i<list.size();i++){
cur.next = new ListNode(list.get(i));
cur = cur.next;
}
cur.next = null;
return pHead;
}