#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
//声明单链表
typedef struct node
{
ElemType data;
struct node *next;
}Node;
//初始化单链表
Node* initList()
{
Node *head = (Node*)malloc(sizeof(Node));
head->data = 0;
head->next = NULL;
return head;
}
//单链表-头插法
Node* inserHead(Node *L,ElemType e)
{
Node *p = (Node*)malloc(sizeof(Node));
p->data = e;
p->next = L->next;
L->next = p;
return p;
}
//单链表-遍历
void listNode(Node *L)
{
Node *p = L->next;
while (p != NULL)
{
printf("%d ",p->data);
p = p ->next;
}
printf("\n");
}
//单链表-尾插法
Node *tailNode(Node *L)
{
Node *p = L;
while (p->next != NULL)
{
p = p->next;
}
return p;
}
Node *insertTail(Node *tailNode,ElemType e)
{
Node *p = (Node*)malloc(sizeof(Node));
p->data = e;
p->next = NULL;
tailNode->next = p;
return p;
}
//单链表-在指定位置插入数据
int insert(Node *L,ElemType e,int pos)
{
//找到插入的位置(前驱节点)
Node *p = L;
int i = 0;
while (i < pos-1)
{
p = p->next;//移动到下一个节点
i++;
if (p==NULL)
{
return 0;
}
}
Node *q = (Node*)malloc(sizeof(Node));
q->data = e;
q->next = p->next;
p->next = q;
return 1;
}
//单链表-删除节点
int delData(Node *L,int pos)
{
//找到插入的位置(前驱节点)
Node *p = L;
int i = 0;
while (i < pos-1)
{
p = p->next;//移动到下一个节点
i++;
if (p==NULL)
{
return 0;
}
}
if(p->next==NULL)
{
printf("要删除的位置错误\n");
}
Node *q = p->next;//q指向要删除的节点
p->next = q->next;//让要删除节点的前驱指向要删除节点的后继
free(q);//释放要删除节点的内存空间
return 1;
}
//单链表-获取长度
void listlen(Node *L)
{
Node *p =L;
int len = 0;
while (p != NULL)
{
p = p->next;
len++;
}
printf("链表长度为%d\n",len);
}
//单链表-释放链表
//1.指针p指向头节点后的第一个节点
//2.判断指针p是否指向空节点
//3.如果p不为空,用指针q记录指针p的后继节点
//4.释放指针p指向的节点
//5.指针p和指针q指向同一个节点,循环操作
void freelist(Node *L)
{
Node *p = L->next;
Node *q;
while (q != NULL)
{
q = p->next;
free(p);
p = q;
}
L->next = NULL;
}
int main()
{
Node *list = initList();
Node *tail = tailNode(list);
tail = insertTail(tail,22);
tail = insertTail(tail,12);
tail = insertTail(tail,32);
tail = insertTail(tail,55);
listNode(list);
insert(list,52,2);
listNode(list);
delData(list,2);
listNode(list);
listlen(list);
freelist(list);
listlen(list);
return 0;
}
数据结构-单链表
发布于 8 天前 33 次阅读
Comments NOTHING