因为这学期C++大作业涉及到了链表、栈和队列,所以这方面知识点记得还比较牢靠,所以先把这些整理下,同时我也会查阅网上相关题目练一下手
本篇主要复习一下链表初始化,头插法及尾插法输入,逆置,以及排序
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node{
int num;
Node *next;
}Node;
Node* init_LinkList(){
Node *head=(Node*)malloc(sizeof(Node));
head->next=NULL;
return head;
}
//头插
Node* Head_Insert(Node *head){
int num;
Node *p;
for(int i=0;i<10;i++){
cin>>num;
p=(Node*)malloc(sizeof(Node));
p->num=num;
p->next=head->next;
head->next=p;
}
return head;
}
//尾插
Node* Tail_Insert(Node *head){
int num;
Node *p, *q;
q=head;
while(q->next!=NULL)
q=q->next;
for(int j=0;j<10;j++){
cin>>num;
p=(Node*)malloc(sizeof(Node));
p->num=num;
p->next=NULL;
q->next=p;
q=q->next;
}
return head;
}
void Show_List(Node *head){
Node *temp=head;
while(temp->next!=NULL){
temp=temp->next;
cout<<temp->num<<" ";
}
cout<<endl;
}
void Reverse_List(Node *head){
Node *p, *q, *r;
//三个Node指针作用分别为:指向头结点,指向正在操作结点,指向正在操作的下一个结点
p=head;
q=head->next;
r=head->next;
p->next=NULL;
while(q!=NULL){
r=q->next;
q->next=p->next;
p->next=q;
q=r;
}
}
void Delete_Node(Node *head, int num){
Node *p, *q;
//p指向待比较结点的前一个结点,q指向正在比较的结点
p=head;
q=p;
while(p->next!=NULL){
q=p->next;
if(q->num==num){
p->next=q->next;
free(q);
continue;
}
p=p->next;
}
}
void Order_List(Node *head){
//先将头结点与其后面分离,头结点指向空,相当于分为两段。后面的结点一个一个往前一段插,挺像头插法的,不过待排序节点需要比较大小,这时候p指针提供插入位置
Node *p, *q, *r;
if(head->next==NULL){
cout<<"链表为空,返回"<<endl;
return;
}
q=head->next;
r=q;
p=head;
p->next=NULL;
while(r!=NULL){
r=r->next;
p=head;
while(p->next!=NULL && p->next->num<=q->num){
p=p->next;
}
q->next=p->next;
p->next=q;
q=r;
}
}
int main(){
Node *A, *B;
A=init_LinkList();
B=init_LinkList();
cout<<"请输入链表A(头插法)"<<endl;
Head_Insert(A);
cout<<"请输入链表B(尾插法)"<<endl;
Tail_Insert(B);
cout<<"链表A如下:"<<endl;
Show_List(A);
cout<<"链表B如下:"<<endl;
Show_List(B);
Reverse_List(A);
Reverse_List(B);
cout<<"逆置后的链表A如下:"<<endl;
Show_List(A);
cout<<"逆置后的链表B如下:"<<endl;
Show_List(B);
int A_delete_num, B_delete_num;
cout<<"请输入A中要删除的数字"<<endl;
cin>>A_delete_num;
cout<<"请输入B中要删除的数字"<<endl;
cin>>B_delete_num;
Delete_Node(A,A_delete_num);
Delete_Node(B,B_delete_num);
cout<<"删除指定数字后的链表A如下:"<<endl;
Show_List(A);
cout<<"删除指定数字后的链表B如下:"<<endl;
Show_List(B);
Order_List(A);
Order_List(B);
cout<<"由小到大排序后的链表A如下:"<<endl;
Show_List(A);
cout<<"由小到大排序后的链表B如下:"<<endl;
Show_List(B);
return 0;
}