leetcode 83. Remove Duplicates from Sorted List

来源:互联网 发布:js 获取复选框选中的值 编辑:程序博客网 时间:2024/05/16 06:43

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.

这道题很简单,就是取出链表的重复元素,遍历一次即可。

代码如下:

/*class ListNode{     int val;     ListNode next;     ListNode(int x) { val = x; }}*/public class Solution {    public ListNode deleteDuplicates(ListNode head)     {        if(head==null || head.next==null)            return head;        ListNode fa=head,son=head.next;        while(son!=null)        {            if(son.val==fa.val)            {                fa.next=son.next;                son=fa.next;            }else            {                fa=son;                son=son.next;            }        }        return head;    }}

下面是C++的做法

代码如下:

#include <iostream>#include <vector>using namespace std;/*struct ListNode{    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};*/class Solution {public:    ListNode* deleteDuplicates(ListNode* h)     {        ListNode* head = new ListNode(-1);        head->next = h;        ListNode* i = head->next;        while (i != NULL)        {            ListNode* j = i->next;            while (j != NULL && j->val == i->val)                j = j->next;            i->next = j;            i = i->next;        }        return head->next;    }};
阅读全文
0 0