Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Idea: This problem is similar to the previous one, the concrete solution is as follows:
/** * 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) {//Remove Duplicates if (p.val = = head.next.val) { head = Head.next; } else{break ; } } Last.next = p;//adds only one value for each item last = Last.next; p = head = Head.next; Last.next = null; } return first.next;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 83.Remove duplicates from Sorted List (delete sort list repetition) thinking and method of solving problems