这个学期刚学数据结构,怎么说呢。感觉不只是数据结构老师,还有很多其他的老师都给我一种这样的感觉-学生啥也不会,啥也不懂。我是觉得非常无语,总感觉数据结构老师把我们小孩子教......
上正文:
#include "windows.h"
#include "iostream"
#include "stdlib.h"
#include "stdio.h"
using namespace std;
typedef struct node{
int data;
struct node *next;
}ListNode, *LinkList;
int InsertList(LinkList head,int i,int e)
{
ListNode *p,*pre;
int j=0;
pre=head;
while (pre->next!=NULL && j<i-1)//找到第i-1个结点
{
pre=pre->next;
j++;
}
if(j!=i-1)
{
cout<<"插入位置出错!"<<endl;
return 0;
}
if((p=(ListNode *)malloc(sizeof(ListNode)))==NULL)
{
exit(-1);
}
p->data=e;
p->next=pre->next;
pre->next=p;
return 1;
}
ListNode* Get(LinkList head,int i)
{
ListNode *p;
int j=0;
p=head;
while (p->next!=NULL && j<i)
{
p=p->next;
j++;
}
if(j==i)
{
return p;
}
else
{
return NULL;
}
}
int main()
{
int num;
int list[]={1,2,5,8,9,12,25,36};
LinkList A;
ListNode *p;
A=(LinkList)malloc(sizeof(ListNode));
//单链表初始化已经完成,请输入要插入的数字
cout<<"--------单链表初始化已经完成,请输入要插入的数字及其插入的位置----------"<<endl;
int insert;
cin>>insert;
cin>>num;
for (int l=1; l<=sizeof(list)/sizeof(int); l++)
{
if(InsertList(A,l,list[l-1])==0)
{
cout<<"位置不合法"<<endl;
return 0;
}
}
InsertList(A,num,insert);
for (int l=1; l<=sizeof(list)/sizeof(list[0]); l++)
{
p=Get(A,l);
if(p)
{
printf("%4d",p->data);
}
cout<<endl;
}
system("pause");
return 0;
}
此代码,从链表的创建,初始化到最后的数据插入都讲解的很详细。废话,我就不多说了,自己看看代码吧。不难!