首页 > 编程 > C++ > 正文

c++ 实现链表的创建,查询,打印,删除,插入

2019-11-06 08:01:41
字体:
来源:转载
供稿:网友
//程序很简单,但是要捋顺逻辑关系,留着备用#include#include"stdafx.h"using namespace std;struct node{int data;node* next;};node * created_head(node *head){node * temp;for (int i = 1; i < 10; i++){temp = new node;temp->data = i;temp->next = head->next;head->next = temp;}return head;}node * created_rear(node *head){node *p2;p2 = new node;p2 = head; //保持头节点node * temp;for (int i = 1; i < 10; i++){temp = new node;//定义一个终端节点temp->data = i;//temp->next = p->next;p2->next = temp;temp->next = NULL;p2 = temp;}return head;}//打印链表void PRint_list(node *head){node *temp;temp = new node;temp = head;while (temp->next != NULL){temp = temp->next;cout << temp->data << "   ";}cout << endl;}//获取链表长度int leng_list(node *head){node *temp;temp = new node;temp = head;int leng = 0;while (temp->next != NULL){temp = temp->next;leng++;}return leng;}//获取链表第i个节点node * get_list(node * head, int i){node *temp;temp = new node;temp = head;bool state = false;int j = 1;while (temp->next != NULL){temp = temp->next;if (j == i){state =true;break;}j++;}if (state == true){cout << "索引成功" << endl;return temp;}else//两种情况, 头指针或者,超过了链表的最大区间{cout << "超出索引范围,返回头结点" << endl;return head;}}//在链表head中第i个位置后插入节点insertvoid insert_list(node *head, int i, node * insert){node *temp;temp = new node;int leng;leng = leng_list(head);if ((i > 0) && (i <= leng)){temp = get_list(head, i);insert->next = temp->next;temp->next = insert;}else{cout << "超出链表范围无法插入" << endl;}}//删除链表head第i个节点void delete_list(node *head, int i){node *temp;temp = new node;node *dele;dele = new node;int leng;leng = leng_list(head);if ((i > 0) && (i <= leng)){temp = get_list(head, i-1);dele = temp->next;temp->next = dele->next;delete dele;}else{cout << "超出链表范围无法删除" << endl;}}void main(){node *head1;node *head2;head1 = new node;head2 = new node;head1->next = NULL;head2->next = NULL;cout << "***************" << "头插法新建链表head1" << "***************" << endl;created_head(head1);print_list(head1);cout << "***************" << "尾插法新建链表head2" << "***************" << endl;created_rear(head2);print_list(head2);cout << endl;cout << "***************" << "链表head1 长度" << "***************" << endl;cout << leng_list(head1) << endl;cout << "***************" << "链表head1 第五个节点" << "***************" << endl;cout << get_list(head1, 5)->data << endl;node * insert;insert = new node;insert->data = 21;cout << "***************" << "head1在第2节点后插入节点insert->data = 21" << "***************" << endl;insert_list(head1,2 , insert);print_list(head1);cout << "***************" << "当前链表head1的长度" << "***************" << endl;cout << leng_list(head1) << endl;cout << "***************" << "删除head1的第5个元素" << "***************" << endl;delete_list(head1, 5);print_list(head1);cout << "***************" << "删除后head1的长度" << "***************" << endl;cout << leng_list(head1) << endl;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选