java 删除单向有序链表中重复的元素 输入一行内输入一串整数,以空格间隔,以# 结束; 输出 一串去重后整数,以空格间隔,以# 结束。
时间: 2024-04-11 14:28:11 浏览: 101
单链表中重复元素的删除
5星 · 资源好评率100%
您可以使用Java编写一个方法来删除单向有序链表中的重复元素。下面是一个示例代码:
```java
import java.util.Scanner;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Node head = null;
Node tail = null;
System.out.println("请输入一串整数,以空格间隔,以#结束:");
while (scanner.hasNext()) {
String input = scanner.next();
if (input.equals("#")) {
break;
}
int num = Integer.parseInt(input);
Node newNode = new Node(num);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
System.out.print("去重后的整数为:");
removeDuplicates(head);
// 打印去重后的链表
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println("#");
}
public static void removeDuplicates(Node head) {
Node current = head;
while (current != null && current.next != null) {
if (current.data == current.next.data) {
current.next = current.next.next;
} else {
current = current.next;
}
}
}
}
```
运行这段代码后,您可以输入一串整数,以空格间隔,以"#"结束。程序将会去除重复的元素并输出去重后的整数序列,以空格间隔,以"#"结束。
注意:输入的整数序列必须是有序的才能正确去除重复元素。
阅读全文