C语言链表的三种插入方式详解
程序员文章站
2022-03-08 20:45:04
...
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef struct Node{
ElementType data;
struct Node *next;
}Node, *LinkList; /*LinkList为结构指针类型*/
void insertHead(LinkList L, ElementType x);//头插法
void insertTail(LinkList L, ElementType x);//尾插法
void insertList(LinkList L, int i, ElementType x);//任意位置插法
int main()
{
LinkList L = createList();
return 0;
}
void insertHead(LinkList L, ElementType x)
{
Node *p;
p = (LinkList)malloc(sizeof(Node));
p->data = x;
p->next = L->next;
L->next = p;
}
void insertTail(LinkList L, ElementType x)
{
Node *pre,*p,*s;
pre = L;
p = L->next;
while(p!=NULL){
pre = p;
p = p->next;
}
s = (Node *)malloc(sizeof(Node));
s->data = x;
s->next = pre->next;
pre->next = s;
}
void insertList(LinkList L, int i, ElementType x)
{
Node *pre, *p, *s;
int k = 1;
pre = L;
p = L->next;
while(p!=NULL && k<i)
{
pre = p;
p = p->next;
k++;
}
s = (Node *)malloc(sizeof(Node));
s->data = x;
s->next = pre->next;
pre->next = s;
}
上一篇: 小程序中下拉刷新页面的功能怎么实现?
下一篇: HTML5面试题PC端和移动端区别