描述
给定一个排序链表,删除所有重复的元素每个元素只留下一个。
您在真实的面试中是否遇到过这个题?
是
样例
给出 1->1->2->null
,返回 1->2->null
给出 1->1->2->3->3->null
,返回 1->2->3->null
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: head is the head of the linked list
* @return: head of linked list
*/
ListNode * deleteDuplicates(ListNode * head) {
// write your code here
if(head==NULL) return head;
ListNode * m_node=head;
int m_num=head->val;
while(m_node->next!=NULL){
if(m_node->next->val==m_num){
m_node->next=m_node->next->next;
}else {
m_num=m_node->next->val;
m_node=m_node->next;
}
}
return head;
}
};