鱼C论坛

 找回密码
 立即注册
查看: 787|回复: 0

[技术交流] C++刷leetcode(面试题 02.01. 移除重复节点)【数据结构】

[复制链接]
发表于 2020-4-11 14:44:47 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2020-5-8 17:49 编辑

题目描述:

  1. 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

  2. 示例1:

  3. 输入:[1, 2, 3, 3, 2, 1]
  4. 输出:[1, 2, 3]
  5. 示例2:

  6. 输入:[1, 1, 1, 1, 2]
  7. 输出:[1, 2]
  8. 提示:

  9. 链表长度在[0, 20000]范围内。
  10. 链表元素在[0, 20000]范围内。
复制代码

  1. #include <iostream>
  2. #include <map>
  3. using namespace std;


  4. struct ListNode{
  5.         int val;
  6.         ListNode* next;
  7.         ListNode(int x) :val(x), next(NULL){
  8.         }
  9. };


  10. void PrintList(ListNode*input){
  11.         ListNode*temp = input;
  12.         while(temp -> next){
  13.                 temp = temp -> next;
  14.                 cout << temp -> val << " ";
  15.         }
  16.         cout << endl;
  17.         cout << "-------------" << endl;
  18. }


  19. ListNode* solution(ListNode* input){
  20.         map<int,int> store;
  21.         ListNode* temp = input -> next;
  22.     ListNode*pre = input -> next;
  23.         while(temp != NULL){
  24.                 store[temp->val] ++;
  25.                 if(store[temp->val] > 1){
  26.                         pre -> next = temp -> next;
  27.                         temp = temp -> next;
  28.             continue;
  29.                 }
  30.                 pre = temp;
  31.         temp = temp -> next;
  32.         }
  33.     return input;
  34. }

  35. int main(void){
  36.         ListNode*input = new ListNode(0);
  37.         ListNode*temp = input;
  38.         cout << "please send numbers for the first singleList:" << endl;
  39.     int number;
  40.     while(cin >> number){
  41.             ListNode* node = new ListNode(number);
  42.             temp -> next = node;
  43.             temp = node;
  44.     }
  45.     PrintList(input);
  46.     ListNode* new_root = solution(input);
  47.     PrintList(new_root);
  48.     return 0;
  49. }
复制代码



注意事项:
1.基本数据结构考察。

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-1 20:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表