删除重复节点
来源:互联网 发布:淘宝知识产权投诉撤销 编辑:程序博客网 时间:2024/06/09 20:19
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
.
Subscribe to see which companies asked this question
思路:后面的与当前的相同删除后面的即可,但是这种方法只能删除连续重复的(即1,1,1这种1,2,1这种无法删除)
代码:
import java.util.ArrayList;/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode node = head; for(;node!=null;node=node.next){ while(node.next!=null&&node.val==node.next.val){ if(node.next==null)node=null; node.next = node.next.next; } } return head; }}递归的(有木有很赞啊!!虽然不是我写的(* ——*))
public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null)return head; head.next = deleteDuplicates(head.next); return head.val == head.next.val ? head.next : head;}
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode pre = new ListNode(-1);//to avoid the head check pre.next = head; ListNode cur = pre; //ListNode node = head; while(cur.next!=null){ if(cur.next.val==cur.val)cur.next = cur.next.next; else cur = cur.next; } return head; }}
0 0
- 单链表删除重复节点
- 删除重复节点
- 删除重复节点
- 单链表删除重复节点
- 从链表中删除重复节点
- 删除链表中重复的节点
- 删除链表中重复的节点
- 删除链表中重复的节点
- 删除链表中重复的节点
- 删除链表中重复的节点
- 删除链表中重复的节点
- 删除链表中重复的节点
- 删除链表中重复的节点
- 删除链表中重复的节点。
- 删除链表中重复的节点
- 删除链表重复节点
- 删除链表中重复的节点
- 删除单链表中的重复节点(删除重复项)
- 目前工程中几种图像存储方式的区别(YUV422I_YUYV&YUV420)
- linux下简单的配置jdk方法
- Large Pool 错误
- 外币兑换
- tcpdump 抓 tcp 包
- 删除重复节点
- caffe训练siamese network
- 【leetcode】107. Binary Tree Level Order Traversal II
- python知识-python操作MySQL数据库
- Android活动的生命周期
- jmeter学习 十 jmeter ftp服务器连接
- String中的trim()方法
- javascript常用判断写法
- Eclipse中Android工程下布局文件无法正常预览