LeetCode OJ 之 Remove Duplicates from Sorted List(删除有序链表中重复的数)
来源:互联网 发布:数据库中自然连接 编辑:程序博客网 时间:2024/04/30 00:49
题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
给定一个有序链表,删除所有重复的数字,使得每个元素只出现一次。
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *deleteDuplicates(ListNode *head) { if(head == NULL) return NULL; ListNode *q=head,*p = head->next; while(p) { while( p && p->val == q->val )//循环结束条件为遇到不等的,或者p为尾结点 { //q->next = p; ListNode *tmp=p; p = p->next ; delete tmp; } if(p)//遇到的是不等的 { q->next = p; q=q->next; p=p->next; } else//一直相等,直到p为尾结点,例如(1,1,1) q->next = NULL;//则令q为尾结点 } return head; }};
代码2:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *deleteDuplicates(ListNode *head) { if (head == nullptr) return nullptr; for (ListNode *prev = head, *cur = head->next; cur; cur = cur->next) { if (prev->val == cur->val) { prev->next = cur->next; //遇到的是相等的,prev则指向相等的结点的后一个,直到遇到不相等的为止 delete cur; } else { prev = cur; } } return head; }};
0 0
- LeetCode OJ 之 Remove Duplicates from Sorted List(删除有序链表中重复的数)
- LeetCode OJ 之 Remove Duplicates from Sorted List II (删除有序链表中重复的数 - 二)
- LeetCode OJ 之 Remove Duplicates from Sorted Array(删除有序数组中重复的数)
- LeetCode OJ 之 Remove Duplicates from Sorted Array II (删除有序数组中重复的数-二)
- [leetcode]Remove Duplicates from Sorted List (删除有序节点的值重复的节点 C语言)
- [LeetCode]83. Remove Duplicates from Sorted List(删除有序链表的重复元素 )
- (LeetCode)Remove Duplicates from Sorted List --- 链表中删除重复元素
- LeetCode | Remove Duplicates from Sorted List(删除链表中重复的数据)
- LeetCode | Remove Duplicates from Sorted Array(删除有序数组的重复元素)
- leetcode-83. Remove Duplicates from Sorted List(删除有序链表中的重复元素)
- Remove Duplicates from Sorted List 删除链表中重复的元素
- Leetcode刷题记——83. Remove Duplicates from Sorted List(删除有序链表的重复结点)
- Leetcode Remove Duplicates from Sorted List II 删除链表中重复的元素II
- LeetCode | Remove Duplicates from Sorted List II(删除链表中重复结点2)
- 删除有序链表的重复元素 Remove Duplicates from Sorted List
- LeetCode OJ:Remove Duplicates from Sorted List
- [LeetCode OJ]Remove Duplicates from Sorted List
- LeetCode OJ Remove Duplicates from Sorted List
- 从贝叶斯方法谈到贝叶斯网络
- 2014.11.13-心情杂
- linux 的C语言 fork()函数
- wp8 怎样让listbox绑定dictionary再通过key找item
- 活动图
- LeetCode OJ 之 Remove Duplicates from Sorted List(删除有序链表中重复的数)
- 心路
- opencv2两张图像拼接融合_基于SURF特征提取
- 在STL中基本容器有: string、vector、list、deque、set、map
- Find Minimum in Rotated Sorted Array II
- 【iOS开发-75】iOS数据存储的三种简单方式:plist、preference以及用NSCoding存储对象
- Openwrt支持挂载nfs文件系统的编译
- GlobalAlloc全局内存的使用
- c/c++笔试题——C++中 new/delete 概念和用法总结