• 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.

    解析:

    开始因为疏忽出现了两次runtime error情况,对于链表的问题一般就是如下情况

    1. NULL->next

    2. 指针是NULL,还用指针的val,p = NULL,p->val

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* deleteDuplicates(ListNode* head) {
    12         if(head == NULL || head->next == NULL)
    13             return head;
    14         ListNode *p = head;
    15         while(p->next)
    16         {
    17             if(p->val == p->next->val)
    18                 p->next = p->next->next;
    19             else
    20                 p = p->next;
    21         }
    22         return head;
    23     }
    24 };
  • 相关阅读:
    UVa 11389
    uva 1418
    uva 10905 Children's Game
    uva 471
    UVA 1508
    Uva120 Stacks of Flapjacks
    UVA 10020 Minimal coverage
    UVA434
    UVa 311
    决策树算法
  • 原文地址:https://www.cnblogs.com/raichen/p/4999974.html
Copyright © 2020-2023  润新知