Leetcode-remove-duplicates-from-sorted-list-ii
来源:互联网 发布:网络经销商合同 编辑:程序博客网 时间:2024/05/18 03:25
题目描述
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.
题目不难,链表操作。
定义一个初始结点指向头结点,然后定义一个cur结点,用于循环往下走的,并把头结点赋值给cur,定义一个pre结点用于记住停留的位置,while循环内,如果cur结点和cur下一个结点值不相等,则pre=cur,否则循环找到不相等的位置,然后pre.next = cur.next;最后cur = cur.next去判断下一个结点。
代码如下:
/** * 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 newnode = new ListNode(head.val-1); newnode.next = head; ListNode cur = head; ListNode pre = newnode; while(cur != null && cur.next != null) { if(cur.val != cur.next.val) { pre = cur; }else{ while(cur.next != null && cur.val == cur.next.val) { cur = cur.next; } pre.next = cur.next; } cur = cur.next; } return newnode.next; }}
0 0
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List II
- LeetCode | Remove Duplicates from Sorted List II
- LeetCode:Remove Duplicates from Sorted List II
- 【leetcode】Remove Duplicates from Sorted List II
- Leetcode: Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- centos maven nexus
- linux命令系列二之目录操作
- Map获取键值,Map的几种遍历方法
- QQ第三方登录示例
- 在创建接口引用指向子类对象时,能否访问Object类中的方法?答案是可以的
- Leetcode-remove-duplicates-from-sorted-list-ii
- 数据结构与算法(7)循环队列
- Ubuntu16.04安装openjdk-7-jdk
- 揭开Gradle的神秘面纱
- JZOJ4693. 【NOIP2016提高A组模拟8.14】疯狂的火神
- Kylin 环境 搭建 成功
- 漫步微积分十九——牛顿法解方程
- Git常用命令使用总结
- 贵定县 计生局办事 太不靠谱 办个手续 推来推去的