其他分享
首页 > 其他分享> > letecode [83] -

letecode [83] -

作者:互联网

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

题目大意:

  给定排序链表,删除其中重复的元素。  

理  解 :

  遍历链表,cur指向当前节点,若它后面的节点A的值与cur的值相等,则删除它后面的节点A,即cur->next指向A后面的节点B;

  若不等,则cur后移一个节点,即cur = cur->next;

代 码 C++:

/**
 * 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;
        int val = head->val;
        ListNode* cur = head;
        while(cur->next!=NULL){
            if(cur->next->val==val){
                cur->next = cur->next->next;
            }else{
                cur = cur->next;
                val = cur->val;
            }
        }
        return head;
        
    }
};

 运行结果:

  执行用时 : 16 ms  内存消耗 : 9.5 MB

标签:head,NULL,ListNode,cur,val,next,83,letecode
来源: https://www.cnblogs.com/lpomeloz/p/10984318.html