c++ 链表的创建与插入

#include<iostream>
using namespace std;
typedef struct link
{
	int e;
	struct link* next;
}Linklist;
 Linklist *init()
{
	 int a[] = { 1,3,5,7,9 };
	 int c;
	 Linklist* head = new Linklist;
	 head->next = NULL;
	 Linklist* r = head; //r为尾指针 始终指向链表尾结点
	 Linklist* pt=NULL;
	 for (int i = 0; i <= 4; i++)
	 {
		 pt = new Linklist;
		 pt->e = a[i];
		 r->next = pt;
		 r = pt;
	 }
	/* cout << "输入" << endl;
	 while (cin >> c, c != 0)
	 {
		 pt = new Linklist;
		 pt->e = c;
		 r->next = pt;
		 r = pt;
		 cout << "输入" << endl;
	 }*/
	 r->next = NULL;//尾指针结点的next置空
	 return head;
}
 void dis(Linklist *head)
 {
	 Linklist *pt = head->next;
	 while (pt!= NULL)
	 {
		 cout << pt->e << endl;
		 pt = pt->next;
	 }
 }
 Linklist* Conduct(Linklist* head,int n)
 {
	 Linklist* pt1 = head->next;//指向第一个有值域的结点
	 
	 Linklist* Node = new Linklist;
	 Node->e = n;
	 Node->next = NULL;
	 if (pt1 -> e>n)//如果第一个结点的值就比n大
	 {
		 Node->next = head->next;
		 head->next = Node;
		 return head;
	 }
	 while (pt1->next != NULL&&pt1->next->e<n)
	 {
		 pt1 = pt1->next;
	 }
	 if (pt1->next == NULL)
		 {
			 pt1->next = Node;
			 return head;
		 }
	 Node->next = pt1->next;
	 pt1->next=Node;
	 return head;
 }
 int main()
 { 
	 Linklist* l = init();
	 dis(l);
	 cout << "输入插入的数值" << endl;
	 int n;
	 cin >> n;
	 Conduct(l, n);
	 cout << "插入数值后的链表" << endl;
	 dis(l);

 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值