Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2Output: 1->2
Example 2:
Input: 1->1->2->3->3Output: 1->2->3
题意
对于有序链表中含有重复值的结点,只保留其中一个。。
思路
遍历就完事了。
代码实现
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/class Solution {public ListNode deleteDuplicates(ListNode head) {ListNode cur = head;while (cur != null) {ListNode temp = cur.next;// 找到第一个与cur结点值不同的结点while (temp != null && temp.val == cur.val) {temp = temp.next;}cur.next = temp;cur = temp;}return head;}}
