#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);
}
c++ 链表的创建与插入
于 2022-09-26 07:53:18 首次发布