leetcode — remove-duplicates-from-sorted-list
2024-10-15 04:55:21
/**
* Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
*
*
* 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.
*/
public class RemoveDuplicates {
/**
* 将链表中重复的元素移除,重复的元素只保留一个
*
* @param head
* @return
*/
public Node remove (Node head) {
Node p = head;
while (p != null && p.next != null) {
if (p.value == p.next.value) {
p.next = p.next.next;
continue;
}
p = p.next;
}
return head;
}
private static class Node implements Comparable<Node>{
int value;
Node next;
@Override
public String toString() {
return "Node{" +
"value=" + value +
", next=" + (next == null ? "" : next.value) +
'}';
}
@Override
public int compareTo(Node o) {
return this.value - o.value;
}
}
private static void print (Node node) {
while (node != null) {
System.out.println(node);
node = node.next;
}
System.out.println();
}
public Node createList (int[] arr) {
if (arr.length == 0) {
return null;
}
Node head = new Node();
head.value = arr[0];
Node pointer = head;
for (int i = 1; i < arr.length; i++) {
Node node = new Node();
node.value = arr[i];
pointer.next = node;
pointer = pointer.next;
}
return head;
}
public static void main(String[] args) {
RemoveDuplicates removeDuplicates = new RemoveDuplicates();
int[] arr = new int[]{1,1,2};
int[] arr1 = new int[]{1,1,2,3,3};
print(removeDuplicates.remove(removeDuplicates.createList(arr)));
print(removeDuplicates.remove(removeDuplicates.createList(arr1)));
}
}
最新文章
- 读取手机上所有应用程序并显示(APP)
- [fortify] open redirect漏洞
- Android屏幕禁止休眠的方法
- dotnet文件操作
- bootloader
- $POST数组论证($GET || $COOKIE || $REQUEST 同理)
- 学习CSS一些事(上)
- 使用POI进行Excel操作的总结一——创建Workbook,Sheet,Row以及Cell
- a标签无disabled属性
- CSS 命名规则
- Chrome浏览器查看cookie
- AAC编码学习
- 使用django 中间件在所有请求前执行功能
- Palindromic characteristics CodeForces - 835D (区间DP,预处理回文串问题)
- 全文检索的Demo
- LeetCode - Unique Email Addresses
- Golang sync
- SqlSession对象之StatementHandler
- SQL语句结合上下文查询(in查询)
- Zookeeper可视化工具
热门文章
- 获取标准shell 命令的输出内容
- imagecreatefrombmp、imagebmp php处理bmp文件
- 关于gulp-sftp上传到服务器
- 查找datatable 中的重复记录(只查询一个字段)
- JAVA---MYSQL 基本知识点 第二部分
- java实现多线程使用多个代理ip的方式爬取网页页面内容
- 请输入一个大于7的整数,输出小于k并且至少满足下面2个条件中的1个条件的所有正整数
- 深入理解Spring Redis的使用 (三)、使用RedisTemplate的操作类访问Redis
- [Swift]LeetCode99. 恢复二叉搜索树 | Recover Binary Search Tree
- [Swift]LeetCode385. 迷你语法分析器 | Mini Parser