Remove Duplicates from Sorted List

来源:互联网 发布:主流的校园网网络拓扑 编辑:程序博客网 时间:2024/05/16 08:05

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

删除链表中的重复点  也是用快慢指针  如果慢指针等于快指针  那慢指针的下一个点等于快指针的下一个点  否则慢指针继续前进。

这题也搞得我好纠结= =绕来绕去的

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {                if(head==null || head.next==null)        return head;        else{        ListNode fast=head.next;        ListNode slow=head;        while(fast!=null){            if(fast.val==slow.val)            {slow.next=fast.next;}            else            {slow=slow.next;}                        fast=fast.next;}            return head;        }            }            }



0 0