1. 程式人生 > >單向鏈表的逆置

單向鏈表的逆置

call alloc div == head turn AS pri while

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

單向鏈表的逆置