实现单链表逆置

 

 

看到笔试和面试里很多这样的题目,于是就练习一下,温故知新。

#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct List
{
   int data;
   struct List *next;
}listNode,*pList;
void createList(pList & list)                   //头插入法建立单链表
{
     pList head=NULL;
     int data;
     cout<<"please input a node:";
     cin>>data;
     list=(struct List *)malloc(sizeof(listNode));
     list->data=data;
     list->next=head;
     head=list;
     while(data!=9)
{
     cout<<"please input a node:";
     cin>>data;
     list=(struct List*)malloc(sizeof(listNode));
     list->data=data;
     list->next=head;
     head=list;

}
} 
void display(pList list)                    //输出单链表
{
     pList temp;
     temp=list;
     while(temp!=NULL)
{
     if(temp->next==NULL)
     cout<<temp->data;
     else
     cout<<temp->data<<"->";
     temp=temp->next;
}
    cout<<endl;

}

void reverseList(pList& list)              //逆置单链表
{
    pList pre;
    pList temp;
    pre=list->next;                        //记录当前节点
    temp=pre->next;                         //记录下一个节点
    list->next=NULL;
    while(pre!=NULL)
{
    pre->next=list;
    list=pre;
    pre=temp;
    if(pre!=NULL)
    temp=temp->next;
     else
     break;   
}
   // pre->next=list;
   // list=pre;
}
int main()
{
    pList list=NULL;
    cout<<"create the list :"<<endl;
    createList(list);
    cout<<"output the list:"<<endl;
    display(list);
    cout<<endl;
    cout<<"reverse the List:"<<endl;
    reverseList(list);
    cout<<"output the reverse list:"<<endl;
    display(list);
    cout<<endl;
    return 0;
}

  

上面逆置算法也可以这样写:

void reverseList(pList& list)             //逆置
{
    pList pre;
    pList temp;
    pre=list->next;                    //记录当前节点
    temp=pre->next;                    //记录下一个节点
    list->next=NULL;
    while(temp!=NULL)
{
    pre->next=list;
    list=pre;
    pre=temp;
    temp=temp->next;  
}
   pre->next=list;
   list=pre;
}

  

截图:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值