首页 > 其他 > 详细

remove-duplicates-from-sorted-list

时间:2019-08-08 13:21:59      阅读:94      评论:0      收藏:0      [点我收藏+]
/**
* Given a sorted linked list, delete all duplicates such that each element appear only once.
* For example,
* Given1->1->2, return1->2.
* Given1->1->2->3->3, return1->2->3.
*
* 给定一个已排序的链接列表,删除所有重复项,使每个元素只出现一次。
* 例如,
* 给出1->1->2,返回1->2。
* 给出1->1->2->3->3,返回1->2->3。
*/

/**
 * Given a sorted linked list, delete all duplicates such that each element appear only once.
 * For example,
 * Given1->1->2, return1->2.
 * Given1->1->2->3->3, return1->2->3.
 *
 * 给定一个已排序的链接列表,删除所有重复项,使每个元素只出现一次。
 * 例如,
 * 给出1->1->2,返回1->2。
 * 给出1->1->2->3->3,返回1->2->3。
 */

public class Main38 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
//        head.next.next = new ListNode(2);
//        head.next.next.next = new ListNode(3);
        System.out.println(Main38.deleteDuplicates(head).val);
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static ListNode deleteDuplicates(ListNode head) {

        ListNode ln = head;
        while (ln != null) {
            while (ln.next != null && ln.val == ln.next.val) {
                ln.next = ln.next.next;
            }
            ln = ln.next;
        }
        return head;
    }
}

  

remove-duplicates-from-sorted-list

原文:https://www.cnblogs.com/strive-19970713/p/11320272.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!