Write code to remove duplicates from an unsorted linked list.
Example1:
Input: [1, 2, 3, 3, 2, 1]
Output: [1, 2, 3]
Example2:
Input: [1, 1, 1, 1, 2]
Output: [1, 2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
List<Integer> list = new ArrayList();
ListNode node = head;
while(node != null) {
list.add(node.val);
node = node.next;
}
List<Integer> list1 = list.stream().distinct().collect(Collectors.toList());
ListNode root = new ListNode(-1);
ListNode cursor = root;
for (int i = 0; i < list1.size(); i++) {
ListNode sumNode = new ListNode(list1.get(i));
cursor.next = sumNode;
cursor = sumNode;
}
return root.next;
}
}
运行结果:运行效率有点低。
注:每次写到链表都要想想怎么构建一个链表。
总结下:经典6步。
// 1、创建一个新的链表root
ListNode root = new ListNode(-1);
// 2、将新的链表root赋值给再新创建的链表cursor。(这一步必须理解)
ListNode cursor = root;
for (int i = 0; i < list1.size(); i++) {
// 3、创建新节点sumNode
ListNode sumNode = new ListNode(list1.get(i));
// 4、将新节点赋值给链表cursor的下一步。(本质是改变root)
cursor.next = sumNode;
// 5、当前节点sumNode赋值给cursor保存
cursor = sumNode;
}
// 6、返回链表root.next
return root.next;
老是说上面的方法不是唯一,只是效率比其他的高些。
里面对第一次接触的人会有些不理解。
可以发现上面我们没有对root做赋值操作。但结果确实改变变了。这个要从引用说起。
例子:
package com.design.bridage;
class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
StringBuilder sbTmp = sb;
sbTmp.append("改变了");
String str = new String();
String strTmp = str;
strTmp = "nihao";
System.out.println(sb.toString());
System.out.println(strTmp);
}
}
运行结果:
理由:StringBuilder sbTmp = sb; sbTmp 保存的是sb引用,你改变sbTmp,就改变了sb。道理类似这个链接哟😄🙂
还有经典的头插法和尾插法:
//从头节点插入,比较简单不用遍历链表
// head 链表 newNode 新节点
public static void insetFromHead(Node head,Node newNode){
newNode.next=head;
head = newNode;
}
//在尾部插入,要遍历链表
// head 链表 newNode 新节点
public static void insertFromTail(Node head1, Node newNode){
Node temp = head1; //用temp代替head去遍历找到最后一个节点,一定不要用head自己去遍历,不然就找不到链表头了
while (temp.next!=null){
temp=temp.next;
}
temp.next=newNode;
}