读书人

leetcode:Remove Duplicates from So

发布时间: 2013-10-22 16:17:14 作者: rapoo

leetcode:Remove Duplicates from Sorted List(去除链表中重复元素)【面试算法题】

题目:

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.

题意去掉链表中重复的元素。



主要就是链表的删除操作,判断当前节点是否和前一个节点值相同,如果相同就删掉。

/** * 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 *pre,*now;        if(!head||!head->next)return head;        pre=head;        now=head->next;        while(now)        {            if(pre->val==now->val)            {                pre->next=now->next;                now=now->next;            }            else            {                pre=now;                now=now->next;            }        }        return head;    }};// blog.csdn.net/havenoidea


题解目录

读书人网 >其他相关

热点推荐