您的位置:首页 > 其它

LeetCode Remove Duplicates from Sorted List II

2016-06-07 18:07 253 查看
题意:给出一个单链表 ,将其中重复的元素删除

思路:在找重复结点时,需要找到其前继结点

代码如下:
class Solution
{
public ListNode deleteDuplicates(ListNode head)
{
ListNode cur = head, next = null, prev = null;

if (null == head) return head;

for (; cur != null; )
{
boolean found = false;
for (next = cur.next; next != null; next = next.next)
{
if (cur.val != next.val)
{
break;
}
else found = true;
}

if (found)
{
if (null == prev)
{
head = next;
cur = head;
}
else
{
prev.next = next;
cur = next;
}
}
else
{
prev = cur;
cur = cur.next;
}
}

return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: