leetcode 83--Remove Duplicates from Sorted List 链表 删除元素

来源:互联网 发布:通过js给html元素赋值 编辑:程序博客网 时间:2024/05/29 19:14

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.
解题思路就是遍历链表,如果2个节点的元素值相等就删掉后一个,否则就移位。尤其注意的是不要直接操作head否则到时候返回的时候head就变了,或者单独保存head进行返回。

/** * Definition for singly-linked list. * public 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 p=head;        while(p!=null&&p.next!=null){            if(p.val==p.next.val){                p.next=p.next.next;            }            else{             p=p.next;            }        }        return head;    }}
0 0