C语言链表学习实例,链表初始化,利用尾指针将两个链表链接在一起。
这个实例中,讲解了如何使用两个单循环链表利用尾指针连接,代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct CLinkList
{
struct CLinkList* next;
int data;
} node;
node* ds_init(node** pNode);
void ds_traverse(node* pNode);
node* connect(node* A, node* B);
node* ds_init(node** pNode)
{
int item;
node* temp;
node* target;
node* r = NULL;
printf("输入结点的值,输入0完成初始化\n");
while (1)
{
scanf("%d", &item);
fflush(stdin);
if (item == 0) {
break;
}
if ((*pNode) == NULL) {
*pNode = (node*)malloc(sizeof(struct CLinkList));
if (!*pNode) {
exit(0);
}
(*pNode)->data = item;
(*pNode)->next = *pNode;
r = *pNode; // 设置尾指针
}
else
{
temp = (node*)malloc(sizeof(struct CLinkList));
if (!temp) {
exit(0);
}
temp->data = item;
temp->next = (*pNode)->next;
(*pNode)->next = temp;
*pNode = temp;
}
}
return r;
}
void ds_traverse(node* pNode)
{
node* temp = pNode;
printf("*****************链表中的元素*********************\n");
do
{
printf("%4d", temp->data);
temp = temp->next;
} while (temp != pNode);
printf("\n");
}
node* connect(node* A, node* B)
{
node* p = A->next;
A->next = B->next;
B->next = p;
return B;
}
int main()
{
node* pHead1 = NULL;
node* A = ds_init(&pHead1);
ds_traverse(pHead1);
node* pHead2 = NULL;
node* B = ds_init(&pHead2);
ds_traverse(pHead2);
connect(A, B);
ds_traverse(pHead1);
return 0;
}