C // 单链表的创建、遍历以及逆置操作

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

typedef struct node {
    int data;
    struct node *next;
}Node;

Node* CreatList()//新建链表
{
    int n,i;
    scanf("%d",&n);
    Node *head,*tail,*p;
    head=tail=NULL;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    for(i=1;i<=n;i++)
    {
        p=(Node *)malloc(sizeof(Node));//在链表建立过程中,p总是不断先接受系统动态分配的新结点地址
        scanf("%d",&p->data);
        p->next=NULL;//由于新增加的节点总是加在链表的末尾,所以该新节点的next域应置为NULL
        if(head==NULL)//建立链表的第一个节点时,整个链表是空的,这时p应该直接赋给head
            head=p;
        else
            tail->next=p;//将原来链表的尾节点的next域指向该新增的节点
        tail=p;//该新增节点成为新的尾节点
    }
    return head;
}
void ShowList(Node *head)//遍历链表
{
    Node *ptr;
    if(head!=NULL)
    {
        for(ptr=head;ptr!=NULL;ptr=ptr->next)//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            printf("%d ",ptr->data);
    }
    printf("\n");
}
Node *ReverseList(Node *head)//逆置列表
{
    Node *p,*q;
    p=head->next;
    while(p)
    {
        q=p;
        p=p->next;//p用来向后移动位置

        q->next = head->next ;//利用head->next的空间作为地址中转站,令q->next指向上一个q所在的位置
        if(q->next==q)//确保原来第二个节点指向原来的第一个节点
            q->next=head;
        head->next = q ;
    }
    head->next=NULL;
    return q;
}

int main(void)
{
    Node *phead;
    phead = CreatList();
    printf("链表逆置前的数据:\n");
    ShowList(phead);
    phead = ReverseList(phead);
    printf("链表逆置后的数据:\n");
    ShowList(phead);
    return 0;
}

发布了12 篇原创文章 · 获赞 12 · 访问量 2967

猜你喜欢

转载自blog.csdn.net/qq_45805420/article/details/104914708
今日推荐