java单链表深拷贝实现
时间: 2024-01-15 10:13:02 浏览: 121
要实现单链表的深拷贝,需要遍历原链表,并对每个节点进行复制操作。以下是Java实现单链表深拷贝的示例代码:
```java
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class LinkedListDeepCopy {
public static ListNode deepCopy(ListNode head) {
if (head == null) {
return null;
}
// 创建新的头节点
ListNode newHead = new ListNode(head.val);
// 创建指针用于遍历新链表
ListNode newNode = newHead;
// 创建指针用于遍历原链表
ListNode curr = head.next;
// 遍历原链表,并复制每个节点
while (curr != null) {
newNode.next = new ListNode(curr.val);
newNode = newNode.next;
curr = curr.next;
}
return newHead;
}
public static void main(String[] args) {
// 创建原链表
ListNode head = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
head.next = node2;
node2.next = node3;
// 进行深拷贝
ListNode deepCopyHead = deepCopy(head);
// 输出拷贝后的链表值
while (deepCopyHead != null) {
System.out.print(deepCopyHead.val + " ");
deepCopyHead = deepCopyHead.next;
}
}
}
```
阅读全文