题目:
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
.
Subscribe to see which companies asked this question
题意:从一个有序的有头结点的链表中删除有且仅有一个的重复元素后返回头结点;
思想:简单的链表操作,遇到下一个元素为重复的时候直接修改当前节点的next指向即可,代码如下
/**
* 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 head;
ListNode* temp = head;
while(temp->next != NULL)
if(temp->next->val == temp->val)
temp->next = temp->next->next;
else
temp=temp->next;
return head;
}
};