删除链表中的重复节点
书中题目:在一个排序的链表中,实现删除重复的节点
力扣83题:给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
此题的思路有些类似 剑指offer-19:删除单向链表的某一指定元素,可以通过遍历,当遇到重复值时,将指针直接指向重复节点的下一个节点即可。
例子:1->2->3->3->4->5
遍历到节点3时,发现它的值与它下一个节点的值重复,判定为它的重复节点,则将当前节点的指针指向节点4继续,循环判断。上代码。
1->2->3 3->4->5
1->2->3->4->5
//力扣-83题:https://leetcode.cn/problems/remove-duplicates-from-sorted-list/
//删除链表中的重复元素
public class DeleteDuplicationNode {
public static ListNode deleteDupNode(ListNode head){
//常规判空
if(head == null){
return null;
}
ListNode cur = head;
//一次遍历,下一个节点不为空时,执行循环
while( cur.getNextNode() !=null){
//获取到当前节点的下一个节点curNextNode
ListNode curNextNode = cur.getNextNode();
//当前节点的值与curNextNode的值相当,这把当前节点的指针指向curNextNode的下一个节点指针
if(cur.getVal() == curNextNode.getVal()){
cur.setNextNode(curNextNode.getNextNode());
}else{
cur = curNextNode;
}
}
return head;
}
public static void main(String[] args) {
// ListNode node5= new ListNode(4);
// ListNode node4= new ListNode(4,node5);
// ListNode node3= new ListNode(3,node4);
// ListNode node2= new ListNode(2,node3);
// ListNode node1= new ListNode(1,node2);
// node1.printNode();
// DeleteDuplicationNode.deleteDupNode(node1);
// node1.printNode();
ListNode node5= new ListNode(4);
ListNode node4= new ListNode(4,node5);
ListNode node3= new ListNode(3,node4);
ListNode node2= new ListNode(1,node3);
ListNode node1= new ListNode(1,node2);
node1.printNode();
DeleteDuplicationNode.deleteDupNode(node1);
node1.printNode();
}
}
数据结构准备:
package com.example.leetcode.dto;
//链表节点
public class ListNode {
private int val;
private ListNode nextNode;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode nextNode) {
this.val = val;
this.nextNode = nextNode;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public ListNode getNextNode() {
return nextNode;
}
public void setNextNode(ListNode nextNode) {
this.nextNode = nextNode;
}
/**
* 测试打印使用
*/
public void printNode(){
ListNode head = this;
while(head != null){
System.out.println(head.getVal());
head = head.getNextNode();
}
System.out.println("-------");
}
}