链表
链表是一种常见的重要的数据结构。 它是动态地进行存储分配的一种结构。 用数组存放数据时必须事先定义固定长度的数组, 如果不确定数组长度必须将数组定义的足够大, 于是很容易造成内存浪费。 而链表没有这种缺点, 它根据需要开辟内存单元。
链表是随机存储的, 在插入, 删除操作上有很高的效率。 但是如果要访问链表中的某个元素的话,那就得从链表的头逐个遍历,直到找到所需要的元素为止,所以链表的随机访问的效率就比数组要低
单链表的实现:
#include<stdio.h> #include<iostream> using namespace std; struct NODE { int data; NODE *next; }; NODE *head = NULL; void Add() { NODE *p1, *p2; printf("please input the data\n >> "); int _data; cin >> _data; p1 = new NODE; if(head == NULL) { head = p1; p1 -> data = _data; p1 -> next = NULL; } else { p2 = head; while(p2 -> next != NULL) { p2 = p2 -> next; } p2 -> next = p1; p1 -> data = _data; p1 -> next = NULL; } cout << "successfully added" << endl; } void Delete() { NODE *p1, *p2; cout << "please input the data" << endl << " >> "; int _data; cin >> _data; bool is = false; if(head == NULL) { cout << "no data" << endl; is = true; } p2 = head; p1 = p2 -> next; if(p2 -> data == _data) { head = p2 -> next; cout << "successfully deleted" << endl; is = true; } else { while(p1 -> data != _data) { p1 = p1 -> next; p2 = p2 -> next; } p2 -> next = p1 -> next; cout << "successfully deleted" << endl; is = true; } if(is == false) { cout << "no this data!" << endl; } } void Change() { cout << "please input the old data" << endl << " >> "; int orgin, _data; cin >> orgin; cout << "please input the new data" << endl << " >> "; cin >> _data; NODE *p1; p1 = head; while(p1 -> data != orgin) { p1 = p1 -> next; } p1 -> data = _data; cout << "successfully changed!" << endl; } void Show() { NODE *p1; p1 = head; while(p1 != NULL) { cout << p1 -> data << " >> "; p1 = p1 -> next; } cout << endl; } int main() { while(1) { printf("1--add, 2--delete, 3--change, 4--show, 5--insert, 6--exit\n >> "); int i1; int flag = 0; cin >> i1; switch(i1) { case 1 : Add(); break; case 2 : Delete(); break; case 3 : Change(); break; case 4 : Show(); break; case 5 : Insert(); break; case 6 : flag = 1; break; } if(flag)break; } return 0; }
时间: 2024-10-20 00:21:46