基本操作
- 创建链表:尾插法和头插法
- 尾插法
#include<iostream>
#include<stdio.h>
using namespace std;
struct node
{
int data;
node *next;
};
//尾插法创建链表
node * create(int Array[])
{
node *head = new node;
head->next = NULL;
node *pre = head;
for(int i=0;i<5;i++)
{
node *p = new node;
p->data = Array[i];
p->next = NULL;
pre->next = p;
pre = p;
}
return head;
}
int main()
{
int Array[5]={3,2,5,1,5};
node *L = create(Array);
L = L->next;
while(L!=NULL)
{
cout<<L->data<<' ';
L = L->next;
}
cout<<endl;
return 0;
}
- 头插法
#include<iostream>
#include<stdio.h>
using namespace std;
struct node
{
int data;
node *next;
};
//头插法创建链表
node * create(int Array[])
{
node *head = new node;
head->next = NULL;
for(int i=4;i>=0;i--)//头插法如果仍然正着插入数据,那么输出的时候数据就会是反的,所以如果想让数据正入正出就需要有插入和输入有一个是反的
{
node *p = new node;
p->data = Array[i];
p->next = head->next;
head->next = p;
}
return head;
}
int main()
{
int Array[5]={3,2,5,1,5};
node *L = create(Array);
L = L->next;
while(L!=NULL)
{
cout<<L->data<<' ';
L = L->next;
}
cout<<endl;
return 0;
}
2、查找元素:已经有了一条链表,查找其中元素x,并输出x的个数
//尾插法的main函数
int num;
cin>>num;
int sum=0;
while(L!=NULL)
{
if(L->data == num) sum++;
L = L->next;
}
cout<<sum<<endl;
3、插入元素和删除元素都一样,有空再写吧