使用c++写一个拷贝整个循环链表到一个新的链表的函数(使用递归,代码完整)
http://blog.csdn.net/a29562268/article/details/53932682 双向链表的实现代码,中间稍改可以达到你的要求。
https://tieba.baidu.com/p/723421403
#include <stdio.h>
#include <malloc.h>
#define MAX_LEN 10
typedef struct _LINKNODE
{
int value;
struct _LINKNODE* next;
}LINKNODE;
void copyLink(LINKNODE** destLink, LINKNODE* sourceLink)
{
if(sourceLink == NULL)
{
destLink = NULL;
return;
}
int count = 0;
LINKNODE* tempSource = sourceLink;
LINKNODE* curNode = NULL;
LINKNODE* temp = NULL;
while(count < MAX_LEN)
{
curNode = (LINKNODE*)malloc(sizeof(LINKNODE));
curNode->value = tempSource->value;
if(*destLink == NULL)
{
*destLink = curNode;
temp = *destLink;
}
else
{
temp ->next = curNode;
temp = temp ->next;
}
tempSource = tempSource->next;
count++;
}
temp->next = sourceLink;
}
void freeLink(LINKNODE* head)
{
int count = 0;
LINKNODE* temp = NULL;
if(head != NULL)
{
while(count++ < MAX_LEN)
{
temp = head;
head = head->next;
free(temp);
}
head = NULL;
}
}
void main()
{
int value[MAX_LEN] = {2, 4, 5, 6, 7, 8, 9, 0, 6, 1};
LINKNODE* head = NULL;
LINKNODE* curNode = NULL;
LINKNODE* copyLink1 = NULL;
LINKNODE* tempCur = NULL;
for(int i=0; i<MAX_LEN; i++)
{
curNode = (LINKNODE*)malloc(sizeof(LINKNODE));
curNode->value = value[i];
curNode->next = NULL;
if(head == NULL)
{
head = curNode;
tempCur = head;
}
else
{
tempCur->next = curNode;
tempCur = tempCur->next;
}
}
tempCur->next = head;
copyLink(©Link1, head);
tempCur = copyLink1;
i = 0;
printf("新的复制后的链表是: ");
while(i < MAX_LEN)
{
printf(" %d ", tempCur->value);
tempCur = tempCur->next;
i++;
}
printf("\n");
freeLink(copyLink1);
freeLink(head);
}