|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2020-5-8 17:49 编辑
题目描述:
- 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
- 示例1:
- 输入:[1, 2, 3, 3, 2, 1]
- 输出:[1, 2, 3]
- 示例2:
- 输入:[1, 1, 1, 1, 2]
- 输出:[1, 2]
- 提示:
- 链表长度在[0, 20000]范围内。
- 链表元素在[0, 20000]范围内。
复制代码
- #include <iostream>
- #include <map>
- using namespace std;
- struct ListNode{
- int val;
- ListNode* next;
- ListNode(int x) :val(x), next(NULL){
- }
- };
- void PrintList(ListNode*input){
- ListNode*temp = input;
- while(temp -> next){
- temp = temp -> next;
- cout << temp -> val << " ";
- }
- cout << endl;
- cout << "-------------" << endl;
- }
- ListNode* solution(ListNode* input){
- map<int,int> store;
- ListNode* temp = input -> next;
- ListNode*pre = input -> next;
- while(temp != NULL){
- store[temp->val] ++;
- if(store[temp->val] > 1){
- pre -> next = temp -> next;
- temp = temp -> next;
- continue;
- }
- pre = temp;
- temp = temp -> next;
- }
- return input;
- }
- int main(void){
- ListNode*input = new ListNode(0);
- ListNode*temp = input;
- cout << "please send numbers for the first singleList:" << endl;
- int number;
- while(cin >> number){
- ListNode* node = new ListNode(number);
- temp -> next = node;
- temp = node;
- }
- PrintList(input);
- ListNode* new_root = solution(input);
- PrintList(new_root);
- return 0;
- }
复制代码
注意事项:
1.基本数据结构考察。 |
|