【LeetCode】083.Remove Duplicates from Sorted List

来源:互联网 发布:魅族手淘宝网的价格 编辑:程序博客网 时间:2024/05/01 17:00

题目:

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.

解答:

类似单链表的遍历。需要注意一点:仅当下个节点和当前节点值不一样时,才跳到下一个节点!!

代码:(顺便吐槽下,这么简单的题提交了3次才AC大哭,链表操作里的细节要格外留意啊)

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {ListNode ret = head;while (head != null && head.next != null) {int currentVal = head.val;int nextVal = head.next.val;if (currentVal == nextVal)head.next = head.next.next;elsehead = head.next;}return ret;}}


0 0
原创粉丝点击