頭插法和尾插法建立單鏈表


//頭插法建立單鏈表 
#include <stdio.h>
#include <malloc.h>

typedef struct LNode{
	int data;
	struct LNode *next;
}Node,*LinkList;

LinkList HeadInsert(LinkList &);	//頭插法建立單鏈表 
void output(LinkList);	//遍歷輸出 

int main(void){
	LinkList L;
	HeadInsert(L);
	output(L);
	return 0;
} 

//頭插法建立單鏈表 
LinkList HeadInsert(LinkList &L){
	L = (Node *)malloc(sizeof(Node));
	L->next = NULL;
	int e;
	scanf("%d",&e);
	while(e != -1){		//輸入-1表示結束輸入 
		Node *s = (Node *)malloc(sizeof(Node));
		s->data = e;
		s->next = L->next;
		L->next = s;
		scanf("%d",&e);
	}
	return L;
}

//遍歷輸出 
void output(LinkList L){
	Node *p = L->next;
	while(p != NULL){
		printf("%d ",p->data);
		p = p->next;
	}
}
//尾插法建立單鏈表 
#include <stdio.h>
#include <malloc.h>

typedef struct LNode{
	int data;
	struct LNode *next;
}Node,*LinkList;

LinkList TailInsert(LinkList &);	//尾插法建立單鏈表 
void output(LinkList);  

int main(void){
	LinkList L;
	TailInsert(L);
	
	output(L);
	return 0;
}


LinkList TailInsert(LinkList &L){		//尾插法建立單鏈表 
	L = (Node *)malloc(sizeof(Node));
	Node *r = L;
	int e;
	scanf("%d",&e);
	while(e != -1){        //輸入-1表示結束輸入 
		Node *s = (Node *)malloc(sizeof(Node));
		s->data = e;
		r->next = s;
		r = s;
		scanf("%d",&e);
	}
	r->next = NULL;
	return L;
}

//遍歷輸出 
void output(LinkList L){
	Node *p = L->next;
	while(p != NULL){
		printf("%d ",p->data);
		p = p->next;
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM