您的位置:首页 > 其它

【LeetCode】Remove Duplicates from Sorted List

2014-12-09 00:08 260 查看

题意:

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
.

思路:

删除链表中的重复项,考察链表操作。

主要是用循环判断当前节点和下一级节点的值是否相同,是则修改当前节点的 next 指针指向下一节点的 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){
        /*保存头指针*/
        ListNode* root = head;

        while(head != NULL)
        {
            /*下一节点存在,且当前节点和下一节点的值重复*/
            while(head->next != NULL && head->val == head->next->val)
            {
                head->next = head->next->next;
            }
            head = head->next;
        }
        return root;
    }
};
Python:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def deleteDuplicates(self, head):
        p = head

        while p != None:
            while p.next != None and p.val == p.next.val:
                p.next = p.next.next
            p = p.next

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