自定义node结构体,实现简单的链表初始化及插入操作
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
int main () {
struct node *head, *p, *q, *t;
int n; //the total number you want to insert
int a;
cin >> n;
head = NULL;
for (int i = 0; i < n; i++)
{
cin >> a;
//动态申请一个空间,用来存放一个节点,并用临时变量p指向这个节点
p = (struct node*)malloc(sizeof(struct node));
p->data = a;
p->next = NULL;
if (head == NULL)
{
head = p;
}
else
{
q->next = p;
}
q = p;
}
t = head;
cout << "当前链表为..." << endl;
while (t != NULL)
{
cout << t->data << " ";
t = t->next;
}
cout << endl;
//----------------------------------------------以下为链表插入操作
//----------------------------------------------插到下一个比它大的元素前
cout << "输入要插入的数" << endl;
cin >> a;
t = head;
while (t != NULL)
{
if (t->next == NULL || t->next->data > a)
{
p = (struct node*)malloc(sizeof(struct node));//动态申请一个
p->data = a;
p->next = t->next;
t->next = p;
break;
}
t = t->next;
}
t = head;
cout << "当前链表为..." << endl;
while (t != NULL)
{
cout << t->data << " ";
t = t->next;
}
system("pause");
}