链表:删除链表中重复的结点(java实现)

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

代码如下:未进行优化


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;
} ListNode realHead = new ListNode(-1);
realHead.next = pHead;
ListNode p = realHead;//存储当前结点的前趋
ListNode q;
q = pHead;//存储当前结点 while(q != null){ int value = q.val;
ListNode l = q.next;
boolean flag = false;
while(l != null && l.val == value){
flag = true;
l = l.next;
}
if(l == null){
if(flag){
p.next = null;
break;
}else{
break;
}
}
if(l.val != value){ if(flag){
p.next = l;
q = l;
l = q.next;
}else{
p = q;
q = l;
l = q.next; }
} } return realHead.next; } /**
* 牛客网:删除链表中重复出现的结点(该程序实现的是将重复出现的值的结点保留一个
* @param pHead
* @return
*/
public ListNode deleteDuplication(ListNode pHead)
{ if(pHead == null){
return null;
}
ListNode p = pHead;//存储当前结点的前趋
ListNode q;
q = pHead.next;//存储当前结点 while(q != null){
if(p.val == q.val){//当前元素已经出现过,则删除该结点
p.next = q.next;
q = p.next;
continue;
}else{
p = q;
q = p.next;
} } return pHead; }
}
上一篇:pandas-11 TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely错误解决方法


下一篇:EF C# ToPagedList方法 The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must ……