您的位置:首页 > 其它

leetcode之Remove Duplicates from Sorted List

2016-04-03 16:54 323 查看
核心思想就是相邻元素逐个比较,遇到相等的就将排在后面的删除。

(1)C语言实现

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     struct ListNode *next;

 * };

 */

struct ListNode* deleteDuplicates(struct ListNode* head) {

    if(head == NULL)

        return NULL;

    struct ListNode* p = head;

    while(p!=NULL && p->next!=NULL){

        if(p->val == p->next->val){

            p->next = p->next->next;

        }

        else

            p = p->next;

    }

    return head;

}

(2)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;

        ListNode* p = head;

        while(p!=NULL && p->next!=NULL){

            if(p->val == p->next->val){

                p->next = p->next->next;

            }

            else

                p = p->next;

        }

        return head;

    }

};

(3)java实现

/**

 * Definition for singly-linked list.

 * public class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode(int x) { val = x; }

 * }

 */

public class Solution {

    public ListNode deleteDuplicates(ListNode head) {

        if(head == null)

            return null;

        ListNode p = head;

        while(p!=null && p.next!=null){

            if(p.val == p.next.val){

                p.next = p.next.next;

            }

            else

                p = p.next;

        }

        return head;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: