zoukankan      html  css  js  c++  java
  • 反转链表

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

    #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("
    ");
    }
    
    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;
    }

    程序运行截图:

  • 相关阅读:
    数据解析1127
    数据解析1119
    数据解析1114
    数据解析1122
    数据解析1121
    数据解析1120
    数据解析1116
    数据解析1128
    Twitter惊现新型病毒 每分钟159条速率分散
    宏达电预计本年有望在台湾市场击败诺基亚
  • 原文地址:https://www.cnblogs.com/areful/p/11323359.html
Copyright © 2011-2022 走看看