[LeetCode]83. Remove Duplicates from Sorted List
题目描述
思路
遍历比较,删除值相同的节点即可
代码
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* cur = head;
while (cur) {
if (cur->next && cur->val == cur->next->val) {
cur->next = cur->next->next;
}
else {
cur = cur->next;
}
}
return head;
}
void printList(ListNode* head) {
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
ListNode* vector2list(vector<int> nums) {
if (nums.size() == 0)
return NULL;
ListNode* head = new ListNode(nums[0]), *iter = head;
for (int i = 1; i < nums.size(); ++i) {
ListNode* temp = new ListNode(nums[i]);
iter->next = temp;
iter = iter->next;
}
return head;
}
};
int main() {
vector<int> nums = { 1,1,1,1,1 };
Solution s;
ListNode* head = s.vector2list(nums);
s.printList(head);
s.printList(s.deleteDuplicates(head));
system("pause");
return 0;
}
10万+




被折叠的 条评论
为什么被折叠?



