数组实现链表及插入

来源:互联网 发布:linux sqlplus 安装 编辑:程序博客网 时间:2024/06/03 19:13

自定义node结构体,实现简单的链表初始化及插入操作

#include <iostream>using namespace std;struct node{int data;struct node *next;};int main () {struct node *head, *p, *q, *t;int n; //the total number you want to insertint a;cin >> n;head = NULL;for (int i = 0; i < n; i++){cin >> a;//动态申请一个空间,用来存放一个节点,并用临时变量p指向这个节点p = (struct node*)malloc(sizeof(struct node));p->data = a;p->next = NULL;if (head == NULL){head = p;}else{q->next = p;}q = p;}t = head;cout << "当前链表为..." << endl;while (t != NULL){cout << t->data << " ";t = t->next;}cout << endl;//----------------------------------------------以下为链表插入操作//----------------------------------------------插到下一个比它大的元素前cout << "输入要插入的数" << endl;cin >> a;t = head;while (t != NULL){if (t->next == NULL || t->next->data > a){p = (struct node*)malloc(sizeof(struct node));//动态申请一个p->data = a;p->next = t->next;t->next = p;break;}t = t->next;}t = head;cout << "当前链表为..." << endl;while (t != NULL){cout << t->data << " ";t = t->next;}system("pause");}


0 0
原创粉丝点击