链表————90.双向链表的逆置

要求说明:实现创建一个双向链表,将双向链表的节点逆置,即将尾节点放到第一个节点的位置,倒数第二个放到第二个节点的位置。依次类推,,并将结果输出。

ps:相对应的双向链表的逆序输出,只要用一个指针遍历到最后一个节点,然后,通过前驱的移位遍历,即可输出,这里就不加入代码了

//双链表逆置
#include <stdio.h>
#include <stdlib.h>


#define N 10


typedef struct node                 //定义结构体,双链结构
{
    char name[20];
    struct node *prior,*next;
}stud;
stud * create(int n)                //双链表创建
{
    stud *p,*h,*s;
    int i;
    h = (struct node *)malloc (sizeof(struct node));        //头节点建立
    h -> name[0] = '\0';                                    //初始化头节点
    h -> prior = NULL;
    h -> next = NULL;
    p = h;                                                  //p指向头节点
    printf("input the records:\n");
    for( i = 1; i <= n; i ++)               
    {
        s = (stud *) malloc (sizeof(stud));                 //申请空间
        scanf("%s",s -> name);                              //数据输入
        p -> next = s;                                      
        s -> prior = p;                                      //指向前驱节点
        s -> next = NULL;                                   //指向后继节点
        p = s;
    }


    return h;                                               //返回头节点
}


stud * reverse(stud *head)      //逆置子函数
{
    stud *p, *r ,*h;
    h = head -> next;           //非头节点的第一个节点 
    if(h && h -> next)          //判断是否第二个节点有存在,存在则进行逆置
    {
        p = h;                  //p指向h
        r = p -> next;          //r指向p的后继
        p -> next = NULL;       //给p的后继赋空,因为逆置,所以此时的p将会是逆置后的最后一个节点
        while(r)                //将p后的节点依次取出放到h的前驱
        {
            p = r;
            r = r->next;
            p -> next = h;
            h -> prior = p;
            h = p;
        }
        head -> next = h;       //头节点指向后继h
        h->prior = head;        //h前驱指向头节点
        return head;            //返回头节点
    }
}
int main(int argc, char **argv)
{
    int n,i;
    int x;
    stud *q;
    printf("input the count of the nodes you want to creat:");  //输入创建的节点数目
    scanf("%d",&n);                     
    q = create(n);              //完成创建
    q = reverse(q);             //完成逆置
    printf("the result linklist:\n");   //逆置后输出
    q = q -> next;
    while(q)
    {
        printf("%s ",&*(q->name));
        q = q->next;
    }
    return 0;
}

样例输入输出:

input the count of the nodes you want to creat:5
input the records:
1 2 3 4 5
the result linklist:
5 4 3 2 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值