版权声明:本文章为博主原创,转载请注明出处。保留所有权利。

Contents
  1. 1. 题目
  2. 2. 解析

Leetcode-278的解题过程。

  • 题目

    Given a sorted linked list, delete all duplicates such that each element appear only once.

    For example,

    1
    2
    Given `1->1->2`, return `1->2`.
    Given `1->1->2->3->3`, return `1->2->3`.
  • 解析

      又是一道Easy级别的题,去除有序链表中重复的节点。基本思想就是遍历链表,如果当前节点的值和下一个节点的值相等,则删除当前节点。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    /**
    * Definition for singly-linked list.
    * public class ListNode {
    * public int val;
    * public ListNode next;
    * public ListNode(int x) { val = x; }
    * }
    */
    public class Solution {
    public ListNode DeleteDuplicates(ListNode head) {
    if (head==null){//边缘情况,这个是经常会犯的错误
    return head;
    }
    ListNode p = head.next;
    ListNode plast = head;
    int temp = head.val;
    while(p!=null){

    if (p.val!=temp){
    temp = p.val;
    plast = plast.next;
    }else{
    plast.next = p.next;
    }
    p = p.next;

    }
    return head;
    }
    }

打赏

取消
扫码支持

你的支持是对我最好的鼓励

Contents
  1. 1. 题目
  2. 2. 解析