[LeetCode][Java] Remove Duplicates from Sorted List II

题意:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinctnumbers from the original list.

For example,Given1->2->3->3->4->4->5, return1->2->5.Given1->1->1->2->3, return2->3.

题目:

给定一个有序链表,删除所有重复的节点,剩余都是原链表中的不相同的节点元素。

比如,

给定1->2->3->3->4->4->5 ,返回1->2->5.

给定1->1->1->2->3 ,返回2->3.

算法分析:

设置前后双指针,后指针遇到重复元素就一直遍历直到重复的结尾,之后前指针指向后指针,,这样就略过所有的重复元素。

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution {public ListNode deleteDuplicates( ListNode head){ListNode pre;ListNode cur;ListNode newhead = new ListNode(0);newhead.next=head;if(head==null||head.next==null)return head;pre=newhead;cur=head;while(cur.next!=null){if(cur.next.val==cur.val)//处理头几个元素相同的例子 如1 1 1 2 3 4{while(cur.next.val==cur.val){cur=cur.next;if(cur.next==null)//处理末尾几个元素相同的例子 1 2 3 4 5 5 5break;}pre.next=cur.next;//pre=pre.next;cur=cur.next;if(cur==null)break;}else//处理头几个元素不相同的例子 1 2 3 4 5{pre=pre.next;cur=cur.next;}}return newhead.next;}}</span>

版权声明:本文为博主原创文章,转载注明出处

看不见我将要去的地方,记不得我已经去过的地方。

[LeetCode][Java] Remove Duplicates from Sorted List II

相关文章:

你感兴趣的文章:

标签云: