题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
代码1:
import java.util.*;
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead == null) return null;
//定义一个链表,存放所有节点的值
ArrayList<Integer> list = new ArrayList<Integer>();
//定义一个头指针
ListNode p = pHead;
list.add(p.val);
while(p.next != null)
{
//滑动指针
p = p.next;
list.add(p.val);
}
//取出存在不重复的值
ArrayList<Integer> list2 = new ArrayList<Integer>();
for(int i : list)
{
int count = 0;
for(int j : list)
{
if(i == j) count ++;
}
if(count == 1) list2.add(i);
}
//重建链表
if(list2.size() == 0) return null;
ListNode pHead2,p2;
pHead2 = new ListNode(list2.get(0));
p2 = pHead2;
for(int i = 1;i < list2.size();i ++)
{
p2.next = new ListNode(list2.get(i));
p2 = p2.next;
}
return pHead2;
}
}
代码2:
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if (pHead == null) {
return null;
}
ListNode headNode = new ListNode(0);
headNode.next = pHead;
ListNode pre = headNode;
ListNode p = pHead;
while(p != null && p.next != null){
if(p.val == p.next.val){
int temp = p.next.val;
while(p != null && p.val == temp){
p = p.next;
}
pre.next = p;
}else{
pre = p;
p = p.next;
}
}
return headNode.next;
}
}