Java实现复制单链表并返回新的头节点
时间: 2024-04-15 16:30:59 浏览: 25
要实现复制单链表并返回新的头节点,可以按照以下步骤进行:
1. 创建一个新的链表头节点,并用一个变量newHead指向它。
2. 创建一个当前节点变量current,初始时指向原链表的头节点。
3. 使用一个循环遍历原链表,直到current为空。
4. 在循环内部,创建一个新的节点newNode,并将current节点的值赋给newNode。
5. 将newNode插入到新链表中,可以使用尾插法或者头插法。
6. 将current指针后移,指向原链表的下一个节点。
7. 循环结束后,返回新链表的头节点newHead。
以下是Java代码示例:
```java
class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
}
public class Main {
public static Node copyLinkedList(Node head) {
if (head == null) {
return null;
}
Node newHead = new Node(head.value);
Node current = head.next;
Node newCurrent = newHead;
while (current != null) {
Node newNode = new Node(current.value);
newCurrent.next = newNode;
newCurrent = newNode;
current = current.next;
}
return newHead;
}
public static void main(String[] args) {
// 创建原链表
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
// 复制链表
Node newHead = copyLinkedList(head);
// 打印新链表的值
Node current = newHead;
while (current != null) {
System.out.print(current.value + " ");
current = current.next;
}
}
}
```
运行上述代码,将输出复制后链表的值:1 2 3。