数据结构
1.链表
关键:头指针实现地址传递。
代码实现一个简单链表:
C语言:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int datd;//可以为你想储存的值的类型
struct node*next;//指针类型,用来存放地址
};
//这里我们可以封装函数来写插入节点和输出也可以写在主函数里
//我们这里用函数来写比较清楚
struct node*head;//这里我们头节点定为全局变量就不用在函数参数中再传入头节点
void insert(int x)//定义一个插入函数
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
if (temp != NULL) {
temp->data = x;
temp->next = head;
} head = temp;
}//头插一个节点
void print()//打印函数定义
{
struct node* t;
t = head;
printf( "this list is :");
while (t != NULL)
{
printf("%d ", t->data);
t = t->next;//继续下一个结点
}//输出链表
}
int main()
{
int i,n,a;
scanf("%d",&n);
struct node*p,*q;//p为中间临时指针
head=NULL;
q=NULL;
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
p = (struct node*)malloc(sizeof(struct node));
if(p!=NULL)
{
p->datd=a;
p->next=NULL;
}
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
return 0;
}
C++:大差不差
#include<iostream>
struct node
{
int datd;//可以为你想储存的值的类型
node*next;//指针类型,用来存放地址
};
//这里我们可以封装函数来写插入节点和输出也可以写在主函数里
//我们这里用函数来写比较清楚
node*head;//这里我们头节点定为全局变量就不用在函数参数中再传入头节点
void insert(int x)//定义一个插入函数
{
node* temp = ( node*)malloc(sizeof(struct node));
if (temp != NULL) {
temp->data = x;
temp->next = head;
} head = temp;
}//头插一个节点
void print()//打印函数定义
node* t;
t = head;
std::cout << "this list is :";
while (t != NULL)
{
printf("%d ", t->data);
t = t->next;//继续下一个结点
}//输出链表
}
int main()
{
int i,n,a;
scanf("%d",&n);
node*p,*q;//p为中间临时指针
head=NULL;
q=NULL;
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
p = ( node*)malloc(sizeof(struct node));
if(p!=NULL)
{
p->datd=a;
p->next=NULL;
}
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
return 0;
}
这里是在链表中任意位置插入一个节点