【LeetCode】C# 83、Remove Duplicates from Sorted List

来源:互联网 发布:建站如何买域名和空间 编辑:程序博客网 时间:2024/06/09 17:11

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.

去除给定有序链表中重复部分。
思路:运用两个指针。fast先走完重复数,后面slow(代表第一个该重复的数)next指向fast的next,如此过滤掉所有重复节点。

/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { val = x; } * } */public class Solution {    public ListNode DeleteDuplicates(ListNode head) {        if(head == null || head.next == null)return head;        ListNode FakeHead = new ListNode(0);        FakeHead.next = head;        ListNode fast = head;        ListNode slow = head;        while (fast != null){            while(fast.next != null && fast.val == fast.next.val)                 fast = fast.next;            slow.next = fast.next;            fast = fast.next;            slow = slow.next;        }        return FakeHead.next;    }}
阅读全文
0 0
原创粉丝点击