public static void main(String[] args){
remove();
}
public static void remove() {
int[] num = {1, 3, 3, 5, 6, 7, 9};
Node head = new Node(num[0]);
Node pre =head;
for (int i = 1;i< num.length;i++){
Node node = new Node(num[i]);
pre.next = node;
pre = node;
}
printLinkNode(head);
Node newHead = deleteDuNode(head);
printLinkNode(newHead);
}
/**
* 链表输出
* @param node
*/
public static void printLinkNode(Node node){
System.out.println(node.data);
if (node.next != null){
printLinkNode(node.next);
}
}
/**
* 链表去重
* @param head
* @return
*/
public static Node deleteDuNode(Node head) {
//首先判断链表是否为空
if (head == null) {
return head;
}
Node node0 = new Node(0);
node0.next = head;
Node pre = node0;
Node p = head;
while (p != null && p.next != null) {
if (p.data == p.next.data){
int val= p.data;
/*
//此while将重复元素全部删除
while (p!=null && p.data == val){
p= p.next;
}
*/
/*
//此while将重复元素删除并留下一个该元素
while (p.next!=null && p.next.data == val){
p.next = p.next.next;
}
*/
pre.next = p;
}else {
pre =p;
p = p.next;
}
}
return node0.next;
}
/**
* 定义链表结构
*/
static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
版权声明:本文为bjxxkjdxcdd原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。