单链表基本操作题目

Description

输入3 4 5 6 7 9999一串整数,9999代表结束,通过头插法新建链表,并输出,通过尾插法新建链表并输出。

Input

3 4 5 6 7 9999,第二行也是3 4 5 6 7 9999,数据需要输入两次

Output

如果输入是3 4 5 6 7 9999,那么输出是7 6 5 4 3,数之间空格隔开,尾插法的输出是3 4 5 6 7

Sample Input 1

3 4 5 6 7 9999
3 4 5 6 7 9999

Sample Output 1

7 6 5 4 3
3 4 5 6 7

Sample Input 2

1 3 5 7 9 9999
1 3 5 7 9 9999

Sample Output 2

9 7 5 3 1
1 3 5 7 9

题解

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

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

void head_insert(LinkList &L){
    
    
	L = (LinkList)malloc(sizeof(LNode));
	L->next = NULL;
	int x;
	LinkList s;
	scanf("%d",&x);
	while(x!=9999){
    
    
		s = (LinkList)malloc(sizeof(LNode));
		s->data = x;
		s->next = L->next;
		L->next = s;
		scanf("%d",&x);
	}
}

void tail_insert(LinkList &L){
    
    
	L = (LinkList)malloc(sizeof(LNode));
	L->next = NULL;
	LinkList s,tail = L;
	int x;
	scanf("%d",&x);
	while(x!=9999){
    
    
		s = (LinkList)malloc(sizeof(LNode));
		s->data = x;
		tail->next = s;
		tail = s;
		scanf("%d",&x);
	}
	tail->next = NULL;
}

void PrintList(LinkList L){
    
    
	L=L->next;
	while(L!=NULL)	
	{
    
    
		printf("%d",L->data);
		L=L->next;
		if(L!=NULL)
		{
    
    
			printf(" ");	
		}
	}
	printf("\n");
}

int main(){
    
    
	LinkList head,tail;
	head_insert(head);
	PrintList(head);
	tail_insert(tail);
	PrintList(tail);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/L6666688888/article/details/128395777