单链表的基本操作

详细请看代码


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct node{
	int va;
	struct node *next;
}Node, *LNode;
int main(){
	LNode p, q, l, L1, L2;
	int k, i, n, jk[100];
	cin >> n;
	L1 = (LNode)malloc(sizeof(Node));
	L2 = (LNode)malloc(sizeof(Node));
	for(i = 1; i <= n; ++i)
		scanf("%d", &jk[i]);
	L1->next = NULL;
	for(i = 1; i <= n; ++i){	//头插
		p = (LNode)malloc(sizeof(Node));
		p->va = jk[i];
		p->next = L1->next;
		L1->next = p;
	}
	q = L2;
	for(i = 1; i <= n; ++i){	//尾插
		l = (LNode)malloc(sizeof(Node));
		l->va = jk[i];
		q->next = l;
		q = l;
	}
	q->next = NULL;
	printf("Head Insert:\n");
	p = L1->next;
	while(p != NULL) {
		printf("%d ", p->va);
		p = p->next;
	}
	printf("\nBehind Insert:\n");
	p = L2->next;
	while(p != NULL) {
		printf("%d ", p->va);
		p = p->next;
	}
	cout << endl;
	while(cin >> k && k){
		q = L2;
		while(q->next != NULL && q->next->va < k) q = q->next;
		l = (LNode)malloc(sizeof(Node));
		l->va = k;
		l->next = q->next;
		q->next = l;
	}
	p = L2->next;
	while(p != NULL) {
		printf("%d ", p->va);
		p = p->next;
	}
	q = L1;					//销毁
	p = L1->next;
	while(p != NULL){
		free(q);
		q = p;
		p = p->next;
	}
	free(q);
	q = L2;
	p = L2->next;
	while(p != NULL){
		free(q);
		q = p;
		p = p->next;
	}
	free(q);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值