好长时间没接触数据结构,有些东西都有点模糊了,今天又温习了一遍
先定义一个结构体
typedef struct LinkList
{
int data;
struct LinkList *next;
}NODE;
那么头结点和头指针是什么呢?
头结点就是指NODE结构体,头结点的指针指向开始结点,对单链表来说,头结点一般作为标记用的,内容为空
头指针是指 指向表中NODE结构体的类型
附程序(比较简单,大家参考参考):
#include
#include
#include
typedef int BOOL;
#define TRUE 1
#define FALSE 0
typedef struct LinkList
{
int data;
struct LinkList *next;
}NODE;
void InitList(NODE **L);
BOOL FindPos(NODE *head,int pos,int *t);
NODE *Insert(NODE *head,int pos,int e);
NODE *Delete(NODE *head,int pos);
void ShowList(NODE *head);
int main(int argc,char **argv)
{
int i = 0;
NODE *lp;
InitList(&lp);
for (i = 0;i < 10; i++)
{
Insert(lp,i+1,i+1);
}
ShowList(lp);
printf("删除元素后\n");
Delete(lp,4);
ShowList(lp);
return 0;
}
void InitList(NODE **L)
{
(*L) = (NODE *)malloc(sizeof(NODE));
if ((*L) == NULL)
{
printf("初始化失败\n");
}
(*L)->data = 0;
(*L)->next = NULL;
printf("Init List success\n");
}
BOOL FindPos(NODE *head,int pos,int *t)
{
NODE *p;
int j = 0;
p = head->next;
while ((p != NULL) && (j < pos))
{
p = p->next;
++j;
}
if ((p == NULL) || (j > pos))
{
return FALSE;
}
*t = p->data;
return TRUE;
}
NODE *Insert(NODE *head,int pos,int e)
{
NODE *p,*q;
int j = 0;
p = head;
while ((p != NULL) && (j < pos - 1))
{
p = p->next;
++j;
}
if ((p == NULL) && (j > pos + 1))
{
return NULL;
}
q = (NODE *)malloc(sizeof(NODE));
q->data = e;
q->next = p->next;
p->next = q;
return head;
}
NODE *Delete(NODE *head,int pos)
{
NODE *p,*q;
int j = 0;
p = head;
while ((p->next != NULL) && (j < pos))
{
p = p->next;
++j;
}
if ((p->next == NULL) && (j > pos))
{
return NULL;
}
q = (NODE *)malloc(sizeof(NODE));
q = p->next;
p->next = q->next;
return head;
}
void ShowList(NODE *head)
{
NODE *p;
p = head->next;
if (p == NULL)
{
printf("链表为空\n");
}
while (p != NULL)
{
printf("%d\t",p->data);
p = p->next;
}
}
阅读(723) | 评论(0) | 转发(0) |