链表:
创建链表的时候可以通过malloc和new来获得若干个结点
首先看下链表的结构体
struct node{//创建链表的结构体
int data;
node *next;
};
malloc用法:
head=(node *)malloc(sizeof(node));
new的用法
head = new node;//创建头结点
下面我们创建一个链表
//创建链表
node *create(int array[],int len)
{
node *p,*pre,*head;//pre保存当前节点的前区节点,head为头节点
head = new node;//创建头结点
head->next=NULL;
pre=head;
for(int i=0;i>len;i++)
{
p=new node;//创建新的结点
p->data=array[i];
p->next=NULL;
pre->next=p;
pre=p;
}
return head;//返回头结点
}
现在插播一下主函数代码
int main()
{
int array[5]={1,2,3,4,5};
node *L;
int len=sizeof(array)/sizeof(int);
L=create(array,len);
L=L->next;
while(L!=NULL)
{
cout<<L->data<<" ";
L=L->next;
}
cout<<endl;
return 0;
}
现在已经创建完成了一个链表,那么下面可以考虑如何查询一个数据是否在链表中
//查询某数据是否存在一个链表中
int search(node *head,int x)
{
int count=0;//计算器
node *p=head->next;
while(p!=NULL)
{
if(p->data==x)
{
count++;
return count;//如果找到了就把他返回
}
p=p->next;
}
return count;
}
链表的插入---在指定的位置插入
//插入数据到链表中去
void insert(node *head,int pos,int x)//在链表中pos的位置插入数据x
{
node *p=head;
for(int i=0;i<pos-1;i++)
{
p=p->next;
}
node *q=new node;//创建新的结点
q->data=x;//数据接入
q->next=p->next;
p->next=q;
}
最后是链表的删除
//删除链表的元素
void del(node *head,int x);//在链表中删除数据x
{
node *p=head->next;//从第一个结点开始枚举
node *pre=head;//pre始终保持head的头指针
while(p!=NULL)
{
if(p->next==x)//找到数据x
{
pre->next=p->next;
free(p);
//或者delete(p)
p=pre->next;
}
else
{
pre=p;
p=p->next;
}
}
}
完整的代码如下
//链表
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct node{//创建链表的结构体
int data;
node *next;
};
//创建链表
node *create(int array[],int len)
{
node *p,*pre,*head;//pre保存当前节点的前区节点,head为头节点
head = new node;//创建头结点
head->next=NULL;
pre=head;
for(int i=0;i<len;i++)
{
p=new node;//创建新的结点
p->data=array[i];
p->next=NULL;
pre->next=p;
pre=p;
}
return head;//返回头结点
}
//查询某数据是否存在一个链表中
int search(node *head,int x)
{
int count=0;//计算器
node *p=head->next;
while(p!=NULL)
{
if(p->data==x)
{
count++;
return count;//如果找到了就把他返回
}
p=p->next;
}
return count;
}
//删除链表的元素
void del(node *head,int x);//在链表中删除数据x
{
node *p=head->next;//从第一个结点开始枚举
node *pre=head;//pre始终保持head的头指针
while(p!=NULL)
{
if(p->next==x)//找到数据x
{
pre->next=p->next;
free(p);
//或者delete(p)
p=pre->next;
}
else
{
pre=p;
p=p->next;
}
}
}
//插入数据到链表中去
void insert(node *head,int pos,int x)//在链表中pos的位置插入数据x
{
node *p=head;
for(int i=0;i<pos-1;i++)
{
p=p->next;
}
node *q=new node;//创建新的结点
q->data=x;//数据接入
q->next=p->next;
p->next=q;
}
int main()
{
int array[5]={1,2,3,4,5};
node *L;
int len=sizeof(array)/sizeof(int);
L=create(array,len);
//L=L->next;
while(L!=NULL)
{
cout<<L->data<<" ";
L=L->next;
}
cout<<endl;
return 0;
}