将单链表H逆置

逆置:是指节点间的关系相反,即前驱变后继而后继变前驱。

算法思路:

依次从原链表中取出每个节点,每次都把该节点作为第一个节点插入另一个新链表中。

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

using namespace std;

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

//建立单链表,返回头结点
struct node * CreateLinkList(){
    char ch ;
    int x ;
    struct node  * head ;
    struct node * r , * P ;
    head = (struct node *)malloc(sizeof(struct node)) ;
    head->next  = NULL ;
    r = head ;
    ch =getchar( ) ;
    while(ch != '*'){
      //  cout<<"ch = " << ch<< endl;
        scanf("%d" , & x) ;
       // cout<<"x = " << x << endl;
        P = (struct node *)  malloc(sizeof(struct node)) ;
        P->data = x ;
        P->next = NULL ;
        r->next = P ;
        r = r-> next ;
        ch = getchar( ) ;
    }
    return head ;
}

//将单链表head逆置,并返回逆置后的链表
struct node * reverseLinkList(struct node * head ){
    struct node *f , * b  , *r;
   // b = (struct node *)malloc(sizeof(struct node));
    f = head->next;
    b->next = NULL ;
    head->next = NULL ;
    while(f != NULL){
        r = f ; //取节点
//        cout<<"f->data = "<< f->data << endl;
//        cout<<"f->next = " << f->next << endl;
        f = f->next ;
        r->next = b->next ; //插入节点
        b->next = r ;
    }
   return b ;
}
int main(){

    cout<< "建立单链表(请输入:[空格]25 45 18 76 29*)"<< endl;
    struct node * rr =CreateLinkList();
    PutOut(rr) ;
    struct node * qq ;
    cout<<"输出逆置的单链表"<< endl;
    qq = reverseLinkList(rr) ;
    PutOut(qq) ;
   return 0 ;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值