CShap 链表去重 源代码
时间: 2023-10-15 13:08:30 浏览: 96
以下是C#语言的链表去重的源代码:
```csharp
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public class LinkedList
{
public Node head;
public LinkedList()
{
this.head = null;
}
public void AddNode(int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
}
else
{
Node current = head;
while (current.next != null)
{
current = current.next;
}
current.next = newNode;
}
}
public void RemoveDuplicates()
{
HashSet<int> set = new HashSet<int>();
Node current = head;
Node previous = null;
while (current != null)
{
if (set.Contains(current.data))
{
previous.next = current.next;
}
else
{
set.Add(current.data);
previous = current;
}
current = current.next;
}
}
public void PrintList()
{
Node current = head;
while (current != null)
{
Console.Write(current.data + " ");
current = current.next;
}
Console.WriteLine();
}
}
public class Program
{
public static void Main()
{
LinkedList list = new LinkedList();
list.AddNode(1);
list.AddNode(2);
list.AddNode(3);
list.AddNode(2);
list.AddNode(4);
list.AddNode(3);
Console.WriteLine("Original List:");
list.PrintList();
list.RemoveDuplicates();
Console.WriteLine("List after removing duplicates:");
list.PrintList();
}
}
```
这里使用了HashSet数据结构来存储已经出现过的元素,然后遍历链表,如果元素已经在HashSet中出现过,则删除该节点,否则将元素添加到HashSet中。
阅读全文