C语言 链表尾插入和逆序

来源:互联网 发布:淘宝美工设计软件 编辑:程序博客网 时间:2024/05/18 02:08

链表逆序只需要一次遍历,用三个指针。


#include <stdio.h>

#include <stdlib.h>

struct Node
{
    char ch;
    struct Node *next;
};

void add(struct Node *head,char ch)//尾插入
{
    struct Node *tmp = head;
    struct Node *newnode;
    while(NULL != tmp->next)
    {
        tmp = tmp->next;
    }
    newnode = (struct Node *)malloc(sizeof(struct Node));
    
    newnode->ch = ch;
    tmp->next = newnode;

    newnode->next = NULL;
}

void reversed_list(struct Node *head)//链表逆序
{
    struct Node *tmp = head->next;
    struct Node *p = head->next->next;
    struct Node *q = p->next;

    while(NULL != q)
    {
        p->next = tmp;
tmp = p;
p = q;        
q = q->next;
    }
    p->next = tmp;
    head->next->next = NULL;
    head->next = p;
}

void print_list(struct Node *head)//显示全部的节点
{
    struct Node *tmp = (head->next);


    while(tmp != NULL)
    {
        printf("%c ",tmp->ch);
tmp = tmp->next;
    }
    printf("\n");
}

void release_all(struct Node **head)//释放所有
{
    struct Node *tmp = (*head);
    struct Node *p;

    while(NULL != tmp->next)
    {
        p = tmp->next;
        tmp->next = p->next;
free(p);
    }
    free(*head);
    (*head) = NULL;
    
}

int main()
{
    struct Node *head;
    char ch;
    int i;
    
    head = (struct Node *)malloc(sizeof(struct Node));
    head->next = NULL;

    for(i = 0; i < 5; i++)
    {
        printf("输入:");
        scanf("%c",&ch);
getchar();
        add(head,ch);
    }

    reversed_list(head);

    print_list(head);

    release_all(&head);

    return 0;

}


0 0