【LeetCode】83. Remove Duplicates from Sorted List

题目:

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 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) {
		ListNode *my_head = new ListNode(0);
		ListNode *current = my_head;
		my_head->next = head;
		while (current->next && current->next->next) {
			ListNode *temp = current->next->next;
			if (current->next->val == temp->val) {
				current->next->next = temp->next;
				delete temp;
			} else {
				current = current->next;
			}
		}
		return my_head->next;
	}
};

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页