对于给定的链接列表,您应该编写一个函数,该函数创建已经创建的链接列表的副本。
示例1:
输入:链接列表:4 6 2 8 1
输出:链接列表的副本:4 6 2 8 1
示例2:
输入:链接列表:4 5 9 8 2
输出:链接列表的副本:4 5 9 8 2
说明:
- 这背后的逻辑只是创建一个新的结构节点,然后将每个现有节点复制到新节点。
- 流程将继续进行,直到现有列表导致null(递归)。
c程序,创建链接列表的副本:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct node
{
int data;
struct node * next;
};
void displayLL(struct node * head)
{
struct node * temp;
temp = head;
temp=head;
while(temp!=0)
{
printf("%d ",temp->data);
temp = temp->next;
}
}
void copy(struct node *head)
{
struct node *temp = head;
struct node *temp1, *temp2, *head1;
temp1 = (struct node *)malloc(sizeof(struct node));
temp1->next = NULL;
temp1->data = temp->data;
head1 = temp1;
temp1->next = NULL;
temp = temp->next;
while(temp != NULL)
{
temp2 = (struct node *)malloc(sizeof(struct node));
temp2->data = temp->data;
temp1->next = temp2;
temp1 = temp2;
temp = temp->next;
}
printf("\n--------------------------------\n");
printf("Copy of original linked list : ");
displayLL(head1);
}
int main()
{
struct node *head = 0, *newnode, *temp;
int n, choice, newdata;
// Create Linked List //
printf("Enter the number of nodes in the list : ");
scanf("%d", &n);
if(n == 0)
{
printf("--------------------------------\n");
printf("Linked list cannot be empty");
exit(0);
}
for(int i = 1; i<=n; i++)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data%d : ", i);
scanf("%d", &newnode->data);
newnode->next = 0;
if(head == 0)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
temp = newnode;
}
}
printf("--------------------------------\n");
printf("Original linked list : ");
displayLL(head);
copy(head);
}
输出:
Enter the number of nodes in the list : 4
Enter the data1 : 3
Enter the data2 : 7
Enter the data3 : 3
Enter the data4 : 8
--------------------------------
Original linked list : 3 7 3 8
--------------------------------
Copy of original linked list : 3 7 3 8