• 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 };
  • 相关阅读:
    工具类-vim在shell中卡死的情况
    tomcat日志分类
    逻辑运算
    牛客练习赛29 F 算式子
    牛客练习赛29 B
    查询
    hdu 5984
    zoj 4057
    zoj 4056
    zoj 4054
  • 原文地址:https://www.cnblogs.com/raichen/p/4999974.html
Copyright © 2020-2023  润新知