zoukankan      html  css  js  c++  java
  • 剑指Offer03 逆序输出链表&链表逆序

    多写了个逆序链表

     1 /*************************************************************************
     2     > File Name: 03_Pirnt_LinkList.c
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: 2016年08月24日 星期三 02时04分25秒
     6  ************************************************************************/
     7 
     8 #include <stdio.h>
     9 #include <malloc.h>
    10 
    11 // 链表结构体
    12 struct ListNode
    13 {
    14     int val;
    15     struct ListNode* next;
    16 };
    17 
    18 // 构造链表
    19 ListNode* createList()
    20 {
    21     struct ListNode* head;
    22     struct ListNode* p;
    23     struct ListNode* q;
    24     head = p = (ListNode*)malloc(sizeof(ListNode));
    25     head->val = 0;
    26     for (int i = 1; i <= 10; ++i)
    27     {
    28         q = (ListNode*)malloc(sizeof(ListNode));
    29         q->val = i;
    30         p->next = q;
    31         p = q;
    32     }
    33     p->next = NULL;
    34     return head;
    35 }
    36 
    37 // 顺序输出链表
    38 void PrintList(ListNode* head)
    39 {
    40     if (head == NULL)
    41         return;
    42     ListNode* temp = head;
    43     printf("PrintList:
    ");
    44     while (temp != NULL)
    45     {
    46         printf("%d ", temp->val);
    47         temp = temp->next;
    48     }
    49     printf("
    ");
    50 }
    51 
    52 // 逆序输出链表
    53 void ReversePrintList(ListNode* head)
    54 {
    55     if (head != NULL)
    56     {
    57         if (head->next != NULL)
    58         {
    59             ReversePrintList(head->next);
    60         }
    61         printf("%d ", head->val);
    62     }
    63 }
    64 
    65 // 逆序链表
    66 ListNode* ReverseList(ListNode* head)
    67 {
    68     if (head==NULL || head->next==NULL)
    69         return head;
    70     ListNode* fast = head->next;
    71     ListNode* slow = head;
    72     slow->next = NULL;
    73     ListNode* temp;
    74     
    75     while (fast->next != NULL)
    76     {
    77         temp = fast->next;
    78         fast->next = slow;
    79         slow = fast;
    80         fast = temp;
    81     }
    82     fast->next = slow;
    83     return fast;
    84 }
    85 
    86 int main()
    87 {
    88     ListNode* test = createList();
    89     PrintList(test);
    90     printf("ReversePrintList:
    ");
    91     ReversePrintList(test);
    92     printf("
    ");
    93     test = ReverseList(test);
    94     PrintList(test);
    95     return  0;
    96 }
  • 相关阅读:
    ptyhon异步开发aiohttp
    python异步编程asyncio
    python ThreadPoolExecutor线程池和ProcessPoolExecutor进程池
    liunx 使用flask + nginx + gunicorn 部署项目
    liunx安装python3.6.8
    Grafana设置mysql为数据源
    使用pyhdfs连接HDFS进行操作
    七、Hadoop搭建Hbase
    六、Zookeeper运行环境
    五、Hadoop搭建Hive
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5801417.html
Copyright © 2011-2022 走看看