头插法-顺序输出,尾插法-反向输出(C语言)

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef struct node{
	int data;
	struct node *next;
}Node, *pNode;

pNode rear_create(int n){//尾插法建立 
	pNode head = (pNode)malloc(sizeof(Node));
	pNode rear = head;//注意与头插法不同地方
	if(head == NULL)
	{
		printf("存储分配失败!\n");
		exit(-1);
	}
	else{
		for(int i=0; i<n; i++){
			pNode pNew = (pNode)malloc(sizeof(Node));
			if(head == NULL)
			{
				printf("存储分配失败!\n");
				exit(-1);
			}
			else{			
				printf("请输入值:");
				scanf("%d", &(pNew->data));
				rear->next = pNew;//注意与头插法不同地方
				pNew->next = NULL;//注意与头插法不同地方
				rear = pNew; //注意与头插法不同地方
			}
		}
	}
	return head;
}

pNode head_create(int n){//头插法建立 
	pNode head = (pNode)malloc(sizeof(Node));
	head->next = NULL;//注意与尾插法不同地方
	if(head == NULL)
	{
		printf("存储分配失败!\n");
		exit(-1);
	}
	else{
		for(int i=0; i<n; i++){
			pNode pNew = (pNode)malloc(sizeof(Node));
			if(head == NULL)
			{
				printf("存储分配失败!\n");
				exit(-1);
			}	
			else{
				printf("请输入值:");
				scanf("%d", &(pNew->data));
				pNew->next = head->next;//注意与尾插法不同地方
				head->next = pNew;//注意与尾插法不同地方				
			}		
		}
	}
	return head;
}

void traverse_list(pNode head){
	pNode p = head->next;
	while(p != NULL){
		printf("%d ", p->data);
		p = p->next;
	}
}

int main() {
	int n;
	printf("请输入链表结点个数n:");
	scanf("%d", &n);
	
	pNode h1 = rear_create(n);
	traverse_list(h1);	//尾插法,实现顺序输出链表 
	printf("\n\n");
	pNode h2 = head_create(n);
	traverse_list(h2);	//尾插法,实现反向输出链表 
	
	return 0;
}

运行结果:
在这里插入图片描述

发布了6 篇原创文章 · 获赞 0 · 访问量 64

猜你喜欢

转载自blog.csdn.net/weixin_38662388/article/details/104671757