找倒数第k个结点
main.c
#include <stdio.h>
#include "LinkListtask.h"
int main()
{
List *ls = CreateList();
if (NULL == ls)
{
printf ("创建链表失败\n");
}
printf ("创建链表成功\n");
int i;
for(i=0;i<9;i++)
{
Insert_Head(ls,i);
}
Display(ls);
int k;
scanf("%d",&k);
Seek_Pos(ls,k);
Display(ls);
Destroy(ls);
return 0;
}
LinkListtask.h
#ifndef _LINKLISTTASK_H_
#define _LINKLISTTASK_H_
typedef enum {TRUE, FALSE, ERROR} BOOL;
typedef int Data;
typedef struct _node
{
Data data; // 数据域
struct _node *next; // 指针域
}Node;
typedef struct _list
{
Node *head;
}
List;
// 创建链表
List* CreateList();
//头插
BOOL Insert_Head(List *ls,Data data);
//k
BOOL Seek_Pos(List *ls,int k);
#endif // _LINKLISTTASK_H_
LinkListtask.c
#include "LinkListtask.h"
#include <stdlib.h>
#include <stdio.h>
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;
}
BOOL Insert_Head(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=ls->head->next;
ls->head->next=node;
return TRUE;
}
BOOL Seek_Pos(List *ls,int k)
{
if(k<1)
return ERROR;
Node *t1=ls->head;
Node *t2=ls->head;
int i;
for(i=0;i<k-1;i++)
{
t1=t1->next;
if(t1==NULL)
{
printf("长度越界:%d\n",k);
return ERROR;
}
}
t1=t1->next;
while(t1!=NULL)
{
t2=t2->next;
t1=t1->next;
}
printf("%-4d\n",t2->data);
return TRUE;
}
void Display(List *ls)
{
if (NULL == ls)
return ;
Node *tmp=ls->head->next;//while里面是tmp,设定tmp=ls->hesd->next
while(tmp)
{
printf("%-4d",tmp->data);
tmp=tmp->next;
}
printf("\n");
}
找中间结点
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;
}
建有环链表,调用main函数时暂时不能使用通用的destroy,因为找不到NULL,destroy程序会一直循环
BOOL Build_Loop(List *ls,int k)//将无环链表改成有环
{
if (NULL == ls||k<1)
return ERROR;
Node *t1=ls->head->next;
Node *t2=ls->head->next;
int i;
for(i=0;i<k-1;i++)//设k为环的起点
{
if(t2==NULL)
{
return ERROR;
}
t2=t2->next;
}
while(t1->next)
{
t1=t1->next;
}
t1->next=t2;
return TRUE;
}
找有没有环
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;
}