题目
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5Output: 1->2->5
Example 2:
Input: 1->1->1->2->3Output: 2->3
题意
将有序链表中所有值重复的结点删除,只保留值不重复的结点。
思路
遍历链表,找到所有值不重复的结点,将其单独取出来依次加入到新链表中。
代码实现
Java
class Solution {public ListNode deleteDuplicates(ListNode head) {ListNode ans = null, last = null;while (head != null) {ListNode temp = head.next;int count = 0;// 判断head的值是否重复,并找到下一个值不同的结点while (temp != null && temp.val == head.val) {temp = temp.next;count++;}if (count == 0) {head.next = null; // 将该结点单独取出,断开与之后结点的联系if (ans == null) {ans = head;last = head;} else {last.next = head;last = last.next;}}head = temp;}return ans;}}
JavaScript
/*** @param {ListNode} head* @return {ListNode}*/var deleteDuplicates = function (head) {const dummy = new ListNode()let p = dummywhile (head) {if (head.next && head.next.val === head.val) {const val = head.valwhile (head && head.val === val) {head = head.next}} else {p.next = headp = headhead = head.nextp.next = null}}return dummy.next}
