码迷,mamicode.com
首页 > 其他好文 > 详细

单向链表的逆置

时间:2018-05-02 02:58:33      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:return   单向链表   free   ||   eof   last   nbsp   int   null   

#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;
}

 

单向链表的逆置

标签:return   单向链表   free   ||   eof   last   nbsp   int   null   

原文地址:https://www.cnblogs.com/dquery/p/8977970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!