#include <stdio.h>
BOOL Insert_Last(List *ls, Data data)
{
if (NULL == ls)
return ERROR;
Node *node = (Node *)malloc(sizeof(Node)/sizeof(char));
if (NULL == node)
return ERROR;
node->data = data;
node->next = NULL;
Node *tmp = ls->head; // 头结点
while (tmp->next)
{
tmp = tmp->next;
}
tmp->next = node;
return TRUE;
}
void Display(List *ls)
{
if (NULL == ls)
return;
Node *tmp = ls->head->next; // 第一个结点
while (tmp)
{
printf ("%-4d", tmp->data);
tmp = tmp->next;
}
printf ("\n");
}
List *CreateList()//创建链表
{
List *ls = (List*)malloc(sizeof(List)/sizeof(char));
if (NULL == ls)
return NULL;
// 创建头结点
ls->head = (Node*)malloc(sizeof(Node)/sizeof(char));
if(NULL == ls->head)
{
free(ls);
return NULL;
}
ls->head->next = NULL; // 空链表
return ls;
}
int OverLap(List *ls1 , List *ls2)//找两个链表重合的点
{
if(NULL == ls1 || NULL == ls2)
return;
Node *tmp1 = ls1->head;
Node *tmp2 = ls2->head;
Node *tmp = ls2->head;
int pos1 = 1;
int pos2 = 1;
while(tmp1->next)
{
tmp1 = tmp1->next; //第一遍指向ls1的第一个结点
//printf("tmp1 = %d\n",tmp1->data);
while(tmp2->next)
{
if(tmp1->data == tmp2->next->data)
return pos1;
pos2++;
tmp2 = tmp2->next;
//printf("pos2 = %d\n",pos2);
}
tmp2 = tmp;
pos2 = 1;
pos1++;
}
return pos1;
}
int Find_K(List *ls , int k)//找一个不知长度的链表的倒数第K个点
{
if(NULL == ls)
return;
int i , count = 0;
Node *tmp1 = ls->head;
Node *tmp2 = ls->head;
for(i = 0; i < k; i++)
{
tmp1 = tmp1->next;
}
while(tmp1->next)
{
tmp1 = tmp1->next;
tmp2 = tmp2->next;
count++;
}
return count;
}
int main()
{
List *ls1 = CreateList();
List *ls2 = CreateList();
if (NULL == ls1 || NULL == ls2)
{
printf ("创建失败\n");
}
printf ("创建成功\n");
int i;
for (i = 0; i < 10; i++)
{
Insert_Last(ls1, i);
}
Display(ls1);
printf("----------------\n");
Insert_Last(ls2, 3);
Insert_Last(ls2, 4);
Insert_Last(ls2, 7);
Insert_Last(ls2, 11);
Insert_Last(ls2, 12);
Display(ls2);
printf("----------------\n");
int a;
a = OverLap(ls1 , ls2);
printf("在链表ls1的第 %d 个位置重合\n", a);
a = Find_K(ls1 , 2);
printf("倒数第K个数是 %d \n", a);
return 0;
}
部分链表题
最新推荐文章于 2022-05-16 23:39:01 发布