反转单链表

csdn第一篇博客,之前的博客一直放在自己的网站上,可是现在觉得wordpress好不方便,还是在CSDN上写吧,从现在开始记录找工作的点点滴滴。

反转单链表,超级热门的面试题,反正我是看到不下十次了,有递归和非递归两种方法

第一种:非递归方法

#include <iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

/*链表结构体*/
struct Node{
    int data;
    struct Node* next;
};
static void reverse(struct Node** head_ref){
    struct Node* prev =NULL;
    struct Node* current =*head_ref;
    struct Node* next;
    while(current!=NULL){
        next =current->next;
        current->next=prev;
        prev=current;
        current=next;
    }
    *head_ref=prev;
}
void push(struct Node** head_ref,int new_data){
    struct Node* new_node=
        (struct Node*)malloc(sizeof(struct Node));

    new_node->data=new_data;

    new_node->next=(*head_ref);

    (*head_ref)=new_node;

}
void printList(struct Node *head){
    struct Node *temp=head;
    while(temp!=NULL){
        cout<<temp->data<<" ";
        temp=temp->next;
    }
}
int main()
{
    struct Node *head=NULL;

    push(&head,2);
    push(&head,4);
    push(&head,6);
    push(&head,8);
    printList(head);
    reverse(&head);
    cout<<endl;
    printList(head);
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值