欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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;
	
}