CG.单链表节点的删除与排序
问题描述】输入一组整数,以单链表的形式存储,删掉里面存放偶数的节点,并按照从小到大的顺序排序,并输出
【输入形式】整数序列,以空格为间隔,最多十个整数
【输出形式】整数序列,以空格为间隔
【样例输入】3 5 8 9 1 2 4
【样例输出】1 3 5 9
【样例说明】
【评分标准】
思路:节点的排序与冒泡排序基本相同,可以采用交换data值而不改变节点值
删除时可以不使用函数,在录入节点时就将其pass掉,符合条件的才能作为data录入
- #include<stdio.h>
- #include<iostream>
- #include<string>
- using namespace std;
- typedef struct node
- {
- int data;
- struct node *next;
- }node;
- node *Creatlist()
- {
- char ch = 0; //停止变量需要初始化
- int n;
- node *head = new node;
- head->next = NULL;
- node *pre = head;
- while(ch!='
') //输入回车后 停止输入
- {
- cin >> n;
- ch = getchar();
- if (n%% 2 != 0) { //只有奇数才纳入节点,不用单独设置删除函数
- node* p = new node; //变量节点
- p->data = n;
- p->next = NULL;
- pre->next = p;
- pre = p;
- }
-
- }
- pre->next = NULL;
- return head;
- }
- void sort(node *head)
- {
-
- int temp;
- for (node *pre = head->next; pre ; pre = pre->next) //循环对比指针需放在1位置
-
- {
- for (node *p = pre->next; p ; p = p->next)
- {
- if (pre->data > p->data)
- {
- temp = pre->data;
- pre->data = p->data;
- p->data = temp;
- }
-
-
- }
- }
-
- }
- void show(node *head)
- {
- node *pre = head->next;
- while (pre)
- {
- cout << pre->data << " ";
- pre = pre->next;
- }
- }
-
- int main()
- {
- node *head = Creatlist(); //函数与变量都是 node*同类型
- sort(head); //排序和输出不需要返回值
- show(head);
- return 0;
- }
tips:输入完毕后 回车结束的设置
- int ch=0;
- while(ch!='
')
- {
- cin>>data;
- ch=getchar();
- ....
-
- }
推荐阅读