实现单向链表的增加、删除、查询、更改、逆序、排序、插入新链表等功能
//实现单向链表的增、删、改、查、插入链表、逆转、排序等功能
#include<iostream>
using namespace std;
class List{
struct Node{
int data;
Node* next;
Node(const int& d):data(d),next(NULL){}
};
List(const List&);
List& operator = (const List&);
Node* head;
public:
List():head(NULL){} //初始化链表
void push_head(const int& d){ //在链表首部添加元素
Node* p=new Node(d);
p->next=head;
head=p;
}
void travel()const{ //链表遍历
Node* p=head;
while(p!=NULL){
cout<<p->data<<' '; //输出链表元素
p=p->next;
}
cout<<endl;
}
void push_tail(const int& d){ //在链表尾部添加元素
if(head==NULL) push_head(d);
else
{
Node* p=head;
while(p->next!=NULL)
p=p->next; //p指向最后一个元素
p->next=new Node(d);
}
}
int size()const{ //获得链表元素的个数
int cnt=0;
Node* p=head;
while(p!=NULL){
++cnt;
p=p->next; //从head遍历到最后一个元素
}
return cnt;
}
Node* & getp(int pos){ //获得元素位置指针
if(pos<0||pos>size()) pos=0;
if(pos==0) return head;
Node* p=head;
for(int i=0;i<pos-1;i++) //操作位置值减2次的次数
p=p->next;
return p->next;
}
void insert(const int&d,int pos=0){ //插入元素
Node* p=new Node(d);
Node* &x=getp(pos); //引用&对原始链表进行操作
p->next=x;
x=p;
}
void rev(){ //链表转置
Node *p=head,*prev=NULL,*back=NULL;
while (p!=NULL)
{
back=p->next;
p->next=prev;
prev=p;
p=back;
}
head=prev; //将head指向转置后的链表头
}
void del(int pos){ //删除一个节点元素
Node* &x=getp(pos-1);
Node* p=x;
x=x->next;
delete p;
}
void sort()const{ //由大到小对链表进行冒泡排序
Node *p1,*p2;
int i,j,temp=0;
for(i=size();i>=1;i--){
p1=p2=head;
p2=p2->next;
for(j=1;j<i;j++){
if(p1->data>=p2->data){ //条件满足交换数据
temp=p1->data;
p1->data=p2->data;
p2->data=temp;
}
p1=p1->next;
p2=p2->next;
}
}
}
void insert(const List&i,int pos){ //将新链表内容插到旧链表的指定位置处
Node * p=i.head;
链表练习题及答案 2页 1下载券喜欢此文档的还喜欢 历年链表考题及答案 14页...算法思想:利用“前插”操作实现链表的逆置,假设把逆置后的链表看成是一个新建...
优点:表中,每个结点的储存地址是可以任意分配的,也就是说,表 中各元素的存储位置可以不连续而且是无序的, 数据元素之间 的逻辑关系由链表中的指针来确定, 可以...
链表练习_计算机软件及应用_IT/计算机_专业资料 暂无评价0人阅读0次下载举报文档 链表练习_计算机软件及应用_IT/计算机_专业资料。3、 (14分)用链表存储一组...
双向链表练习 暂无评价 2页 1下载券 c++语言链表练习 8页 免费 链表习题 3页 1下载券 链表 习题 4页 1下载券 第一讲链表习题 6页 1下载券 链表+指针...
链表练习 隐藏>> 文件:/home/tarena/.cache/.fr-cS8qf9/day09/listex.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23...
链表练习 ...隐藏>> (9)程序 #include <stdio.h> struct stu { int x; int *y; } *p; int d[4]={10,20,30,40}; struct stu aa[4]={50,...
几个小的链表练习题 栈 链表 队列的练习题栈 链表 队列的练习题隐藏>> 3.3 写出下列程序段的输出结果(栈的元素类型 SelemType 为 char) 。 void main(){...
第一讲链表习题_工学_高等教育_教育专区。第一讲练习题重点习题 0 基本概念 1、 静态链表中指针表示的是 (六、2(2 分) 】 A.内存地址 B.数组下标. C....
热门文档