C语言链表的三种插入方式详解

#include
#include

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 && knext;
		k++;
	}
	s = (Node *)malloc(sizeof(Node));
	s->data = x;
	
	s->next = pre->next;
	pre->next = s;
	
}

 

你可能感兴趣的:(C语言)