剑指offer上写的是去除重复元素,且重复元素不保留。
思路,因为输入的head不是头结点,是第一个元素。所以,新建一个结点,用两个指针first和pre指向这个新结点,first做头结点,固定不动,pre每次移动。
public class Solution {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
Solution solution = new Solution();
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(3);
ListNode l5 = new ListNode(4);
ListNode l6 = new ListNode(4);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
l5.next = l6;
ListNode res = solution.deleteDuplication(l1);
while(res!= null){
System.out.println(res.val);
res = res.next;
}
}
public ListNode deleteDuplication(ListNode head)
{
if(head == null || head.next == null){
return head;
}
ListNode first = new ListNode(-1);
first.next = head;
ListNode pre = first;
ListNode p = head;
while(p != null && p.next!=null){
if(p.val == p.next.val){
int val = p.val;
while( p != null && p.val == val){
p = p.next;
}
pre.next = p;
}else{
pre = p;
p = p.next;
}
}
return first.next;
}
}
还有另外一种题型,保留重复结点。
链表去重,没什么好讲的,主要思路就是判下一个结点是否为空,不为空就判值是否和当前结点相等。
下面是只做了去重,重复元素保留了的版本。
注意:while循环条件需要判断cur != null 和cur.next != ,不能只判断cur.next != null。(原因是cur.next = cur.next.next这一步执行后cur为null时,此时cur.null会报错)
/*
* @lc app=leetcode.cn id=83 lang=java
*
* [83] 删除排序链表中的重复元素
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode cur = head;
while(cur != null && cur.next != null ){
if(cur.val == cur.next.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
// @lc code=end