zoukankan      html  css  js  c++  java
  • 单向链表的逆置

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    
    typedef struct list LIST; 
    struct list
    {
        int data; 
        struct list *next;
    };
    
    
    void print_list(struct list *p)
    {
    
        struct list *head = p;
        while (head)
        {
            printf("data = %d
    ", head->data);
            head = head->next;
        }
    
    }
    
    //单向链表的逆置
    void reverse(struct list *p)
    {
        if (p == NULL)
            return;
    
        if (p->next == NULL || p->next->next == NULL)
            return;
    
        struct list *last = p->next;
    
        struct list *cur = p->next;
        struct list *pre = p;
        struct list *next = NULL;
    
        while (cur)
        {
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        p->next = pre; //未逆置前的首节点指向尾节点
        last->next = NULL;
    }
    
    
    int main()
    {
        struct list* p1 = calloc(1, sizeof(struct list));
        struct list* p2 = calloc(1, sizeof(struct list));
        struct list* p3 = calloc(1, sizeof(struct list));
        struct list* p4 = calloc(1, sizeof(struct list));
        struct list* p5 = calloc(1, sizeof(struct list));
        p1->data = 1;
        p1->next = p2;
    
        p2->data = 2;
        p2->next = p3;
    
        p3->data = 3;
        p3->next = p4;
    
        p4->data = 4;
        p4->next = p5;
    
        p5->data = 5;
        p5->next = NULL;
    
        reverse(p1);
        print_list(p1);
    
        free(p5);
        free(p4);
        free(p3);
        free(p2);
        free(p1);
        return 0;
    }
  • 相关阅读:
    事件的解密
    C#世界中的委托
    这次是C#中的接口
    完全二叉树的建立和翻转
    全排列的应用
    网易笔试-按位或运算
    柱状图的最大矩形--单调栈
    Linux将线程绑定到CPU内核运行
    Windows多线程与线程绑定CPU内核
    B+树介绍
  • 原文地址:https://www.cnblogs.com/dquery/p/8977970.html
Copyright © 2011-2022 走看看