单链表

来源:互联网 发布:最新全国地区数据库 编辑:程序博客网 时间:2024/06/04 01:03

单链表逆序算法:

分析:

  1). 若链表为空或只有一个元素,则直接返回;

  2). 设置两个前后相邻的指针p,q. 将p所指向的节点作为q指向节点的后继;

  3). 重复2),直到q为空

  4). 调整链表头和链表尾

示例:以逆序A->B->C->D为例,图示如下

 

#include<iostream>using namespace std;class node{public:int value;node * next;};class linkList{private:node *head;//头结点node *pcuur;public:linkList(){head=pcuur=new node;}~linkList(){};void add(int data);void insert(int x,int data);void delete_num(int x);void showList();void reverse_linkList();};void linkList::delete_num(int x){node *p,*q;p=head->next;int i=1;while (p && i<(x-1)){p=p->next;i++;}q=p->next->next;p->next=q;}void linkList::insert(int x,int data)//在链表的x位置插入数据data{node *p,*q,*t;p=head->next;int i=1;while (p && i<(x-1)){p=p->next;i++;}t=new node;t->value=data;q=p->next;p->next=t;t->next=q;}void linkList::add(int data){if(head->next==NULL){pcuur=new node;pcuur->value=data;head->next=pcuur;pcuur->next=NULL;}else{pcuur->next=new node;pcuur=pcuur->next;pcuur->value=data;pcuur->next=NULL;}cout<<"添加节点成功"<<endl;}void linkList::showList(){node *pNode;pNode=head->next;if(pNode==NULL){cout<<"空指针,无法输出链表值"<<endl;}while(pNode!=NULL){cout<<pNode->value<<endl;pNode=pNode->next;}}void linkList::reverse_linkList(){node *p,*q,*t;p=head->next;q=head->next->next;t=NULL;if (p==NULL||q==NULL){cout<<"此单链表不需要逆序"<<endl;}while (q!=NULL){t=q->next;q->next=p; p=q;q=t;}head->next->next=NULL;//设置链表尾head->next=p;//修改链表头}int main(){linkList l;l.add(1);l.add(2);l.add(3);l.add(4);l.add(5);cout<<"逆转链表之前"<<endl;l.showList();l.insert(5,6);cout<<"插入数据之后"<<endl;l.showList();l.delete_num(5);cout<<"删除数据之后"<<endl;l.showList();l.reverse_linkList();cout<<"逆转链表之后"<<endl;l.showList();return 0;}


 

 

 

 

原创粉丝点击