版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82813404
问题
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
输入: 1->1->2
输出: 1->2
输入: 1->1->2->3->3
输出: 1->2->3
Given a sorted linked list, delete all duplicates such that each element appear only once.
Input: 1->1->2
Output: 1->2
Input: 1->1->2->3->3
Output: 1->2->3
示例
public class Program {
public static void Main(string[] args) {
var head = new ListNode(1) {
next = new ListNode(1) {
next = new ListNode(2) {
next = new ListNode(3) {
next = new ListNode(3)
}
}
}
};
var res = DeleteDuplicates(head);
ShowArray(res);
Console.ReadKey();
}
private static void ShowArray(ListNode list) {
var node = list;
while(node != null) {
Console.Write($"{node.val} ");
node = node.next;
}
Console.WriteLine();
}
private static ListNode DeleteDuplicates(ListNode head) {
if(head == null) return null;
var cur = head;
var next = cur.next;
while(cur != null && next != null) {
while(next != null && cur.val == next.val) {
next = next.next;
}
cur.next = next;
cur = next;
next = cur?.next;
}
return head;
}
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
}
以上给出1种算法实现,以下是这个案例的输出结果:
1 2 3
分析:
显而易见,以上算法的时间复杂度为: 。