这几天一直在看链表,刚开始有点迷糊,看了两天,后来发现链表实际上挺简单的,主要掌握住,怎么判断链表为空,链表怎么表示,增删改查操作时,应该怎么操作当前结点,注意内存泄漏,掌握住了以上几点,链表应该就差不多了,废话不多说,直接撸代码。
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(int x){
data=x;
next=NULL;
}
};//创建一个节点类,也可以使用struct结构体
class Linklist{
private:
Node *head;
public:
void insert(Node *node,int index){
if(head==NULL){
head=node;
return;
}//判断是否是空链表,true的话就令当前结点为头结点,返回
if(index==0){
node->next=head;
head=node;
return;
}//判断插入结点的位置是否是头结点,true的话就令头结点为当前结点的后继(需先腾出头结点的位置),当前结点为头结点
Node *current=head;//记录当前结点的位置
int i=0;
while(current->next!=NULL && i<index-1){
current=current->next;
i++;
}//遍历链表
if(i==index-1){
node->next=current->next;
current->next=node;
}//若遍历到要插入位置的前一结点,即可插入结点
}
void output(){
if(head==NULL){
return ;
}
Node *current=head;
while(current!=NULL){
cout<<current->data<<" ";
current=current->next;
}//遍历输出
cout<<endl;
}
void deleteNode(int del_index){
if(head==NULL){
return;
}//判断链表是否为空
Node *current=head;
int i=0;
if(del_index==0){
head=head->next;
delete current;
return;
}//判断删除的结点是否是头结点
while(current->next!=NULL && i<del_index-1){
current=current->next;
i++;
}//遍历
if(i==del_index-1){
Node *del_node=current->next;//这里为什么不能不分配地址,直接delete current->next?可以试试删除第5个结点试试,
current->next=current->next->next;//这样会导致后一个结点的地址索引没了
delete del_node;
}//取出删除结点,释放空间
}
void changeNode(int cha_index,int n){
Node *current=head;
int i=0;
while(current->next!=NULL && i<cha_index-1){
current=current->next;
i++;
}
if(i==cha_index-1){
current->next->data=n;
}
}
int queryNode(int queIndex){
Node *current=head;
int i=0;
int res;
while(current->next!=NULL&&i<queIndex-1){
current=current->next;
i++;
}
if(i==queIndex-1){
res=current->next->data;
}
return res;
}
};
int main(){
Linklist l1;
for(int i=1;i<=10;i++){
Node *node1=new Node(i);//给结点分配地址
l1.insert(node1,i-1);//插入结点
}
cout<<endl;
cout<<"l1:"<<endl;
l1.output();
//l1.deleteNode(5);
//l1.changeNode(1,12);
cout<<l1.queryNode(1)<<endl;
//l1.output();
return 0;
}