数据结构实验之链表三:链表的逆置

来源:互联网 发布:清华大学网络 编辑:程序博客网 时间:2024/05/20 19:47


这道题的算法思想就是先建立一个顺序链表,然后再建一个空表,在head和head->next之间不断插入新的结点。

代码如下:

#include <stdio.h>
#include <malloc.h>
struct node{
    int data;
    struct node* next;
};
void Putlist(struct node* head){/*输出函数*/
    struct node* p;
    p=head->next;
    while(p){
        if(p==head->next)
            printf("%d",p->data);
        else
            printf(" %d",p->data);
        p=p->next;
    }
}
struct node* Reverselist(struct node* head){/*链表逆置函数,在head和head->next之间插入新的节点*/
    struct node* p,*q;
    p=head->next;
    head->next=NULL;/*建立新表*/
    while(p){
        q=p->next;
        p->next=head->next;//在head和head—>next之间插入节点
        head->next=p;//插入节点
        p=q;//把要插入的下一个结点赋给其前一个结点*/
    }
    return head;
};
int main(){
    int n,i;
    struct node* head,*tail,*p;
    head=(struct node*)malloc(sizeof(struct node));
    tail=head;
    while((scanf("%d",&n))&&n!=-1){/*建立一个顺序链表*/
          p=(struct node*)malloc(sizeof(struct node));
          p->data=n;
          p->next=NULL;
          tail->next=p;
          tail=p;
    }
    head=Reverselist(head);
    Putlist(head);
    return 0;
}

1 0
原创粉丝点击