Leetcode solutions: remove duplicates from sorted list I & II

Source: Internet
Author: User

Remove duplicates from sorted list


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.

/*** 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) {If (Head = NULL | head. next = NULL) return head; listnode visited = head; while (visited! = NULL & visited. Next! = NULL) {If (visited. Val = visited. Next. Val) visited. Next = visited. Next. Next; else visited = visited. Next;} return head ;}}


Remove duplicates from sorted List II


Given a sorted Linked List, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,


Given 1-> 2-> 3-> 3-> 4-> 5, return 1-> 2-> 5.
Given 1-> 1-> 1-> 2-> 3, return 2-> 3.

 
/*** 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) {If (Head = NULL | head. next = NULL) return head; listnode pre = new listnode (0); pre. next = head; head = pre; while (pre. next! = NULL) {listnode cur = pre. Next; while (cur. Next! = NULL & cur. next. val = cur. val) cur = cur. next; If (pre. next = cur) {// don't find the duplicatepre = pre. next;} else {// remove the duplicate nodepre. next = cur. next;} return head. next ;}}



Leetcode solutions: remove duplicates from sorted list I & II

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.