Lintcode:删除排序链表中的重复元素

版权声明:本文未经博主允许不得转载。 https://blog.csdn.net/pianzang5201/article/details/90910739

问题:

给定一个排序链表,删除所有重复的元素每个元素只留下一个。

样例:

样例 1:
	输入:  null
	输出: null


样例 2:
	输入: 1->1->2->null
	输出: 1->2->null

样例 3:
	输入: 1->1->2->3->3->null
	输出: 1->2->3->null

python:

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: head is the head of the linked list
    @return: head of linked list
    """
    def deleteDuplicates(self, head):
        # write your code here
        if head == None or head.next == None:
            return head
        curNode = head
        while curNode.next != None:
            if curNode.val == curNode.next.val:
                curNode.next = curNode.next.next
                continue
            curNode = curNode.next
        return head

C++:

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

猜你喜欢

转载自blog.csdn.net/pianzang5201/article/details/90910739