反转链表

许久不用链表,一些基本操作都生疏了。写一个反转单向链表的小程序练一下:

 

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    struct Node* next;
    unsigned int index;
} Node, *PNode;

static PNode createNode()
{
    PNode node = (PNode) malloc(sizeof(Node));
    node->next = NULL;
    return node;
}

static void printList(PNode node)
{
    PNode p = node;
    while(p)
    {
        printf("%d ", p->index);
        p = p->next;
    }
    printf("\n");
}

static void deleteList(PNode node)
{
    PNode p = node;

    while(p != NULL)
    {
        PNode next = p->next;

        p->next = NULL;
        free(p);

        p = next;
    }
}

static PNode reverseList(PNode head){
    PNode pre = NULL, cur = head, next;

    while(cur){
        next = cur->next;
        cur->next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
}

int main()
{
    PNode head= createNode();
    head->index = 0;

    PNode cur = head;
    for(int i=1; i<10; i++){
        cur->next = createNode();
        cur->next->index = i;
        cur = cur->next;
    }

    printList(head);

    head = reverseList(head);
    printList(head);

    deleteList(head);

    return 0;
}

 

程序运行截图:

 

posted on 2019-08-08 19:42  areful  阅读(172)  评论(0编辑  收藏  举报

导航