单向链表的逆置

Posted 逆风天堂886

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单向链表的逆置相关的知识,希望对你有一定的参考价值。

#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\n", 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语言实现单链表的逆置?