zoukankan      html  css  js  c++  java
  • 遍历链表

    题目截图:

    思路:

      链表详解请查看另一篇博客。只需要在输入数据的同时按序插入链表即可。

     

    代码如下:

     1 /*
     2     遍历链表 
     3 */
     4 
     5 #include <stdio.h>
     6 #include <string.h>
     7 #include <math.h>
     8 #include <stdlib.h>
     9 #include <time.h>
    10 #include <stdbool.h>
    11 
    12 // 链表结构定义 
    13 typedef struct _node {
    14     int data;                // 数据域 
    15     struct _node* next;        // 下一个结点 
    16 } node; 
    17 
    18 int main() {
    19     int n;
    20     while(scanf("%d", &n) != EOF) {
    21         node *head, *p, *pre;                    // 头结点、当前结点、前置结点 
    22         int temp, i;
    23         head = (node*)malloc(sizeof(node));        // 创建头结点 
    24         head->next = NULL;                        // 链表初始为空 
    25         for(i=0; i<n; ++i) {                    // 输入 n 个数 
    26             scanf("%d", &temp);
    27             // 创建新结点 
    28             node* newNode = (node*)malloc(sizeof(node));
    29             newNode->data = temp;
    30             if(i==0) {                            // 第一个结点,直接插入 
    31                 head->next = newNode;
    32                 newNode->next = NULL;
    33             } else {                            // 不是第一个结点,需要查找插入位置 
    34                 pre = head;
    35                 p = head->next;
    36                 while(p != NULL && temp > p->data) {    // 查找插入位置 
    37                     pre = p;
    38                     p = p->next;
    39                 }
    40                 pre->next = newNode;                    // 插入新结点 
    41                 newNode->next = p;
    42             }
    43         }
    44         p = head->next;                            // 指向第一个结点 
    45         for(i=0; i<n; ++i) {                    // 按要求遍历输出 
    46             printf("%d", p->data);
    47             if(i != n-1) {
    48                 printf(" ");
    49             }
    50             p = p->next;
    51         }
    52         printf("
    "); 
    53     }
    54 
    55     return 0;
    56 }
  • 相关阅读:
    数据库的连接、会话与SQLite
    数据库的连接
    SQlite的结构——存储管理
    数据库 schema含义
    SQLite这么娇小可爱,不多了解点都不行啊
    简析打开数据库流程
    计算机系为什么要学数据库原理和设计?
    SQLite的sqlite3_prepare_v2
    Sqlite3并发读写注意事项
    SQLite也可能出现死锁
  • 原文地址:https://www.cnblogs.com/coderJiebao/p/HustTest13.html
Copyright © 2011-2022 走看看