0、为链表节点(动态)分配内存空间、释放
C++下面的new使用方便,比较推荐
//malloc的申请方式
typename* p = (typename*)malloc(sizeof(typename));
int *p = (int*)malloc(sizeof(int));
node *p = (node*)malloc(sizeof(node));
//new的申请方式(c++中的)
typename* p = new typename;
int *p = new int;
node *p = new node;
//释放
free(p);//----malloc
delete(p);//----new
1、创建链表
//创建链表
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
node* next;
};
node* creat(int Array[]){//node* 这是这个函数返回的类型
node *p,*pre,*head;//pre保存当前节点的前驱节点
head = new node;
head->next = NULL;
pre = head;
for(int i = 0;i <5;i++){
p = new node;
//将Array[i]赋给新建的节点作为数据域,也可以scanf输入
p->data = Array[i];
p->next = NULL;//新节点的指针域为null
pre->next = p;//前驱节点的指针域设为当前新建节点的地址
pre = p;
}
return head;//返回头结点指针
}
int main(){
int Array[5] = {5,3,6,1,2};
node *L = creat(Array);//新建链表,返回的头指针head赋给L
L = L->next;
while(L != NULL){
printf("%d",L->data);
L = L->next;
}
return 0;
}
2、查询、新增、删除
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
node* next;
};
//创建链表
node* creat(int Array[]){//node* 这是这个函数返回的类型
node *p,*pre,*head;//pre保存当前节点的前驱节点
head = new node;
head->next = NULL;
pre = head;
for(int i = 0;i <13;i++){
p = new node;
//将Array[i]赋给新建的节点作为数据域,也可以scanf输入
p->data = Array[i];
p->next = NULL;//新节点的指针域为null
pre->next = p;//前驱节点的指针域设为当前新建节点的地址
pre = p;
}
return head;//返回头结点指针
}
//在以head为头结点的链表上计数元素x的个数
int search(node *head,int x){
int count = 0;
node *p = head->next;
while(p != NULL){
if(p->data == x){
count++;
}
p = p->next;
}
return count;
}
//将x插入以head为头结点的链表的第pos个位置上
void insert(node *head,int pos,int 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;
}
//删除以head为头结点的链表中所有数据域为x的节点
void del(node* head,int x){
node *p = head->next;
node *pre = head;
while(p != NULL){
if(p->data == x){
pre->next = p->next;
delete(p);
p = pre->next;
}
else{//数据域不是x,把pre和p都后移一位
pre = p;
p = p->next;
}
}
}
//主体
int main(){
int Array[13] = {5,3,6,1,2,3,3,4,8,9,9,8,9};
node *L = creat(Array);//新建链表,返回的头指针head赋给L
L = L->next;
while(L != NULL){
printf("%d ",L->data);
L = L->next;
}
printf("\n---------------分割线--------------\n");
node *M = creat(Array);//重新得到头指针
printf("%d这个数字出现了%d次\n",3,search(M,3));
printf("\n---------------分割线--------------\n");
M = M->next;
insert(M,3,10);//在3位置上插入10
printf("\n在3位置插入10:\n");
while(M != NULL){
printf("%d ",M->data);
M = M->next;
}
printf("\n---------------分割线--------------\n");
node *N = creat(Array);
N = N->next;
del(N,9);//删除所有的9
printf("\n删除所有的9:\n");
while(N != NULL){
printf("%d ",N->data);
N = N->next;
}
return 0;
}