利用C语言实现链表的前插和后插:

#define _CRT_SECURE_NO_WARNINGS 1
#include 
#include 
typedef struct node{
	int data;
	struct node next;
}Lnode,*LinkList;
//前插法:
LinkList Inserthead(){
	LinkList L;
	Lnode* s;
	int flag = 1;
	char c;
	int count = 0;

	L = (LinkList)malloc(sizeof(Lnode));
	L->next = NULL;
	while (flag){
		scanf("%c", &c);
		if (c != '$'){
			s->data = c;
			L->next = s;
			L = s;
			count++;
		}
		else{
			flag = 0;
			L->data = count;
			L->next = NULL;
		}
		
	}
	return L;
}
//后插法:
LinkList Insertlast(){
	LinkList L;
	Lnode* s;
	int flag = 1;
	char c;
	int count = 0;

	L = (LinkList)malloc(sizeof(Lnode));
	L->next = NULL;
	while (flag){
		scanf("%c", &c);
		if (c != '$'){
			s->data = c;
			L->next = s;
			s->next = NULL;
			L = s;
			count++;
		}
		else{
			flag = 0;
			L->data = count;
		}

	}
	return L;
}
int mian(){
	Inserthead();
	system("pause");
	return 0;
}

两种方法改变的只是头结点后尾结点的指针的指向。

你可能感兴趣的:(C-数据结构与算法)