/*
头插法定义链表
*/
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
/*
当使用数据结构体类型时
struct data{//学生类型
double name;//姓名
int num;//学号
int math;//分数
}
*/
using namespace std;
struct Node{
int data;
struct Node*next;
};
struct Node*createList(){//创建链表
struct Node*headNode=(struct Node*)malloc(sizeof(struct Node));//创建动态存储
//headNode 成为的结构体变量
//变量前必须初始化
headNode->data=1;//头结点初始化,开始时也可以不给初始化
headNode->next=NULL;
return headNode;
}
struct Node*createList(int data){//创建节点 ,创建节点的数据是多少————data
struct Node*newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
void printList(struct Node*headNode){//打印链表 ,打印哪一个链表(eg.打印headNode为头节点的链表)
struct Node*pMove=headNode->next;
while(pMove){
cout<<pMove->data;
pMove=pMove->next;
}
cout<<"\n";
}
void insertNodeByHead(struct Node*headNode,int data){//插入节点
//插入到哪一个链表(headNode为头节点的链表,插入的数据)
//1创建插入的节点
struct Node*newNode=createList(data);
newNode->next=headNode->next;
headNode->next=newNode;
}
void deleteNodeByAppoin(struct Node*headNode,int posData){//删除节点
/*
删除节点以指定位置删除,指定位置为对应的数data
*/
struct Node*posNode=headNode->next;
struct Node*posNodeFront=headNode;//PosNode的上一个节点
if(posNode==NULL)cout<<"NULL!!!"<<endl;
else{
while(posNode->data!=posData){
posNodeFront=posNode;
posNode=posNodeFront->next;
if(posNode==NULL){
cout<<"END!!!"<<endl;
return;
}
}
posNodeFront->next=posNode->next;
free(posNode);
}
}
int main(){
struct Node*list=createList();
insertNodeByHead(list,1);
insertNodeByHead(list,2);
insertNodeByHead(list,3);
insertNodeByHead(list,4);
/*
当使用数据结构体时
insertNodeByHead(list,名字,学号,分数);
*/
printList(list);
deleteNodeByAppoin(list,2);//数据结构体时改变
printList(list);
system ("pause");
return 0;
}