赞
踩
指针这一块的确实博大精深,不愧是c的精髓
一个字妙啊!
- /*
- struct Node {
- int Element; // 节点中的元素为整数类型
- struct Node * Next; // 指向下一个节点
- };
- 从键盘输入5个整数,将这些整数插入到一个链表中,并按从小到大次序排列,最后输出这些整数。
- 5 3 4 2 1
- 1 2 3 4 5
- */
- #include<iostream>
- using namespace std;
- typedef struct node
- {
- int data;
- struct node* next;
- }*lnode;
- //建立单链表
- void createNode(lnode &head)
- {
- lnode p; int x;//定义节点p和值x
- head = new node;//为头结点开辟空间,用head接收
- head->next = NULL;//为头结点的下一个赋空
- cout << "输入5个节点的值,输入9999退出循环" << endl;
- int k = 0;
- while (1)//while循环创立下一个节点
- {
- //if (x == 9999) break;
- if (k == 5) break;
- cin >> x;
- p = new node;//p与head首先无关联
- p->data = x;
- p->next = head->next;
- head->next = p;
- k++;
- }
-
- }
- //遍历链表
- void track(lnode head)
- {
- lnode p ;
- for ( p = head->next; p!=NULL; p = p->next)
- cout << p->data<<" ";
- }
- //计算链表长度
- int calculateLength(lnode head)
- {
- int count = 0;
- lnode p = head->next;
- while (p)
- {
- count++;
- p = p->next;
- }
- return count;
- }
- //查 统计链表中待查找元素的个数
- int search(lnode head,int x)
- {
- lnode p = head->next;
- int count = 0;
- while (p)
- {
- if (p->data == x) count++;
- p = p->next;
- }
- return count;
- }
- //增 链表的元素插入.在pos处插入元素x
- void insert(lnode head, int pos, int x)
- {
- lnode p = head;
- for (int i = 0; i < pos; i++)//0号位置是head的下一个元素
- {
- p = p->next;
- }
- lnode t = new node;
- t->data = x;
- t->next = p->next;
- p->next = t;
- }
- //删 删除表中所有元素等于x的值
- void Delete(node *head, int x) {
- node *pre, *p;
- pre = head;
- p = head->next;
- while (p) {
- if (p->data = x) {
- pre->next = p->next; //删除p所指向的结点
- delete p;
- p = pre->next; //重新给p赋值
- }
- else {
- pre = p; //pre永远指向待删结点的前一个
- p = p->next;
- }
- }
- }
-
- int main()
- {
- lnode head,p,q;
- createNode(head);
- //冒泡排序
- /*cout << "开始排序" << endl;
- int n = 5;
- for (int i = 0; i < 5; ++i) {
- p = head->next;
- for (int j = 0; j < 4 - i; ++j) {
- if (p->data > p->next->data) {
- int temp = p->data;
- p->data = p->next->data;
- p->next->data = temp;
- }
- p = p->next;
- }
- }*/
- //在0号位置插入999
- insert(head, 0, 999);
- //遍历链表
- cout << "排序结果:" << endl;
- track(head);
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。