无序链表的去重问题

给定一个链表,无序的,去除其中重复的数字后返回。

solution1:哈希表法:建立一个哈希表,遍历链表的节点,哈希表中已经存在该节点的就删除,否则将其加进哈希表中。时间复杂度O(n).空间负责度O(256)

solution2:若不能申请额外的空间,即空间复杂度为0,则双层遍历链表中的节点,当前节点与已经遍历过的节点之前的链表比较。若相等就删除否则继续往下遍历。

第一种方法的代码:

class solution{

public:

            ListNode * DeleteDuplicates(ListNode * head)

{

ListNode *pre=NULL, * cur=head;

int m[256]={0};

while(cur)

{

if(m[cur->val]>0)

pre->next=cur->next;

else

{pre=cur;

cur=cur->next;

}

}

return head;

}

};

第二种方法的代码:

class solution{

public:

             ListNode * DeleteDuplicates(ListNode * head)

{

ListNode * com=head, *cur=head;

while(com)

{ cur=com->next;

ListNode * pre=cur;

while(cur)

{

if(cur->val==com->val)

pre->next=cur->next;

else

{ pre=cur;

cur=cur->next; }

}

com=com->next;

}

          return head; 

}

};


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
无序单链表去重操作可以使用哈希表来实现。具体步骤如下: 1. 定义一个哈希表,用于记录链表中已经出现过的元素。 2. 遍历链表节点,对于每个节点,首先在哈希表中查找该节点的值是否存在。 3. 如果哈希表中已存在该值,则说明链表中已经有相同的元素,将该节点从链表中删除;如果哈希表中不存在该值,则将该值添加到哈希表中,继续遍历下一个节点。 4. 最终,遍历完整个链表后,链表中的重复元素都已经被删除。 具体实现的代码如下所示: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构 struct ListNode { int val; struct ListNode* next; }; void removeDuplicates(struct ListNode* head) { if (head == NULL) { return; } // 定义哈希表 int hashSet[1000] = {0}; struct ListNode* pre = head; struct ListNode* cur = head->next; // 遍历链表节点 while (cur != NULL) { // 如果哈希表中已存在该值,则删除当前节点 if (hashSet[cur->val] != 0) { pre->next = cur->next; free(cur); cur = pre->next; } else { // 否则将该值添加到哈希表中 hashSet[cur->val] = 1; pre = cur; cur = cur->next; } } } // 创建一个链表节点 struct ListNode* createNode(int val) { struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode)); node->val = val; node->next = NULL; return node; } // 打印链表 void printList(struct ListNode* head) { struct ListNode* cur = head; while (cur != NULL) { printf("%d ", cur->val); cur = cur->next; } printf("\n"); } int main() { // 创建链表示例:1->2->3->2->4->3 struct ListNode* head = createNode(1); head->next = createNode(2); head->next->next = createNode(3); head->next->next->next = createNode(2); head->next->next->next->next = createNode(4); head->next->next->next->next->next = createNode(3); printf("原始链表:"); printList(head); removeDuplicates(head); printf("去重后的链表:"); printList(head); return 0; } ``` 以上代码就可以实现对无序单链表进行去重操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值