如何删除单链表中的重复结点
方法一:递归
对于一个结点head,首先把链表head->next作为头结点的链表中的重复项删除,然后遍历head->next为头结点的链表中的元素,判断遍历到的元素是否与head结点元素相等,如果相等,则删除。对于head->next为头结点的链表而言,可以使用同样的思路来删除以head->next->next为头结点的链表中的重复元素。因此可以使用递归的方法求解
struct ListNode {
int val;
ListNode *next;
};
ListNode* delSame(ListNode* head)
{
ListNode* pointer = head;
ListNode* temp = head;
if (head->next == NULL)
{
return head;
}
head->next = delSame(head->next);
pointer = head->next;
while (pointer != NULL)
{
if (head->data == pointer->data)
{
temp->next = pointer->next;
free(pointer);
pointer = temp->next;
}
else
{
pointer = pointer->next;
temp = temp->next;
}
}
return head;
}
方法二:hash
- 建立一个hash_map,key为链表中已经遍历的结点内容,开始时为空
- 从头开始遍历链表中的结点。如果结点内容在hash_map中存在,则删除此结点,继续向后遍历;如果结点内容不再hash_map中,则保留此结点,将结点内容添加到hash_map中,继续向后遍历