LeetCode -- Remove Duplicates from Sorted List, leetcode

Source: Internet
Author: User

LeetCode -- Remove Duplicates from Sorted List, leetcode

 

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

For example,
Given1->1->2, Return1->2.
Given1->1->2->3->3, Return1->2->3.

 

The LeetCode is a simple question. when processing the linked list, only one repeated value is retained in the linked list. The general process is as follows:

1. First, judge whether the linked list is empty or there is only one node. If yes, return directly. Otherwise, perform general processing.

2. The head is the previous node, and the nextNode is the next node pointed to by the rear head. If the nextNode is not empty, it indicates that it does not reach the end of the linked list and enters the while loop.

3. Note that when head. val = nextNode. val is over two duplicate values, point the next node of the head to the next node of the nextNode, and remove the nextNode. The head node remains unchanged.

Head. val! = NextNode. val, head moves to nextNode.

Finally, assign nextNode to the next node to which next points, and continue the cyclic comparison.

 

 

/** * 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 result = head;        if(head==null||head.next==null)            return head;        else{            ListNode nextNode = head.next;            while(nextNode!=null){            if(head.val == nextNode.val)                head.next = nextNode.next;            else                head = nextNode;            nextNode = head.next;            }        }        return result;    }}

 




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.