题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
源代码:
解法一://没有通过
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.HashMap;
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
ListNode pre=null,next=null;
if(pHead==null||pHead.next==null) return pHead;
pre=pHead;
//pHead=pHead.next;
while(pHead!=null&&pHead.next!=null){
pHead=pHead.next;
if(pre!=pHead&&pHead!=pHead.next){
pre.next=pHead;
//m.put(pHead,1);
}
}
return pre;
}
}
解法二:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.HashMap;
public class Solution {
public ListNode deleteDuplication(ListNode pHead){
ListNode pre=null;
if(pHead==null||pHead.next==null) return pHead;
pre=pHead;
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
while(pre!=null){//遍历链表,并对每个元素的出现次数计数,注意这里对重复出现的元素的计数方式
if(hash.containsKey(pre.val)){
int cnt=hash.get(pre.val);
hash.remove(pre.val);
hash.put(pre.val,cnt+1);
}else{
hash.put(pre.val,1);
}
pre=pre.next;
}
ListNode prenew=pHead;
ListNode resnode=null;
ListNode tmp = null;
boolean flag=false;
while(prenew!=null){//遍历链表,对每个节点,判断其出现次数,如果出现次数只有一次,则加入到新的链表中,如果出现次数大于一次,则不加入到链表中
if(hash.get(prenew.val)==1){
if(tmp==null){
tmp=prenew;
resnode=tmp;//标记头节点
}else{
tmp.next=prenew;
tmp=tmp.next;
}
flag=true;//如果链表中有元素当且仅当出现过一次,则标记为true
}
prenew = prenew.next;
}
if(flag==false) return null;//如果链表中所有的元素都是重复出现,则返回空值
tmp.next=null;//链表中最后一个节点的next域必须设置为空
return resnode;
}
}