之前学过的c和c++最难的就是指针了,其实指针本身不难,其实就是记录的地址,但是他千变万化,所以,凡是涉及指针的数据结构都很难,如果不深入理解,勤加练习,即使当前理解了,再过段时间依然不能正确地编码,所以有必要时常地进行带有指针的数据结构的练习,比如常规的二叉树、链表等等,当然,以上数据结构也可以用其他方法实现,之后再记录一下吧。
代码功能,创建出一个递增的序列存入链表中,再插入一个数,链表仍是有序的。
#include <cstdio>#include <iostream>
using namespace std;
struct node
{
int data;
struct node* next;
};
int main()
{
int n,num,in_num;
struct node *p,*head,*q,*t;
head = NULL;
while(cin>>n)
{
while(n--)
{
cin>>num;
node *p = new node;//c++申请内存用法, 数据类型 *p = new 数据类型
p->data = num;
p->next = NULL;
if(head == NULL)
head = p;
else
q->next = p;
q = p;
}
t = head;
while(t != NULL)
{
cout<<t->data<<" ";
t = t->next;
}
cout<<endl;
cout<<"Please input the insert number"<<endl;
cin>>in_num;
t = head;
while(t != NULL)
{
if(t->next->data >= in_num)
{
node *p = new node;
p->data = in_num;
p->next = t->next;
t->next = p;
break;
}
t = t->next;
}
t = head;
while(t != NULL)
{
cout<<t->data<<" ";
t = t->next;
}
}
}