Leetcode 82.Remove duplicates from Sorted List II (delete sort list repeat II) thinking and method of solving problems

Source: Internet
Author: User

Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from the Original list.

For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.

Idea: This question in just start to do when thinking of a bit, how can not be solved correctly. Rewrite all of the code to remove it later. The idea is to record the current node P=head, then head down, and when the head value is not equal to the value of Head.next, it ends. Compare P==head, equal description not repeated, connected. The inequality indicates that there are repeated, skipping on it can be.

Detailed code such as the following:

/** * Definition for singly-linked list. * public class ListNode {*     int val; *     ListNode Next; *     listnode (int x) {val = x;}}} */public class Soluti On {public    ListNode deleteduplicates (ListNode head) {        ListNode first = new ListNode (0);        ListNode last = first;                ListNode p = head;                while (head = null) {        while (head.next! = null) {//p does not move, head moves back until Head.next and p are unequal        if (p.val = = head.next.val) {        Head = head.next;//equal loop        }else{        break;//Not Equal end        }        if (p = = head) {//Only one        Last.next = p;/ /Join Last        = Last.next;        }        p = head = head.next;//There are multiple then do not join        last.next = null;//Remove association        }return first.next;}    }



Leetcode 82.Remove duplicates from Sorted List II (delete sort list repeat II) thinking and method of solving problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.