#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;
}
1.寻找第k个结点
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;
}
2.寻找链表的中点
BOOL Middle_Pos(List *ls)
{
Node *t1=ls->head->next;
Node *t2=ls->head->next;
while(t2!=NULL&&t2->next!=NULL)
{
t2=t2->next->next;
t1=t1->next;
}
printf("%-4d\n",t1->data);
return TRUE;
}
3.判断有没有环
BOOL Loop(List *ls)
{
if (NULL == ls)
return ERROR;
Node *t1=ls->head;
Node *t2=ls->head;
while(t2!=NULL&&t1!=NULL)
{
t1=t1->next->next;
t2=t2->next;
if(t1==t2)
{
return TRUE;
}
}
return ERROR;
}
4.找到两个链表重合的点
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;
}