链表逆转

今天实现了单链表逆转的递归和非递归实现方法,把代码贴出来。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
 
struct node {
    int v;
    struct node *next;
};
 
 
/*非递归逆转*/
int reverse(struct node **head)
{
    if(!head || !(*head)) return -1;
    struct node *pre, *cur, *nex;
    pre = NULL, cur=*head;
    while(cur) {
        nex = cur->next;
        cur->next = pre;
        pre = cur;
        cur = nex;
    }
    *head = pre;
    return 0;
}
 
 
/*递归逆转*/
struct node* reverse2(struct node* head)
{
    struct node *p1, *p2;
    if(!head || !(head->next)) return head;
    p1 = head;
    p2 = p1->next;
    head = reverse2(p2);
    p2->next = p1;
    p1->next = NULL;
    return head;
}
 
 
int printfList(struct node* head)
{
    struct node *p;
    p = head;
    while(p) {
        printf("%d\t", p->v);
        p = p->next;
    }
    printf("\n");
    return 0;
}
 
 
#if 1
/*test*/
int main()
{
    int i;
    struct node *head = NULL;
    struct node *p;
 
    for(i = 0; i < 16; i++) {
        if (head) {
            p = (struct node*) malloc(sizeof(*p));
            p->v = i;
            p->next = head;
            head = p;
        } else {
            head = (struct node*) malloc(sizeof(*head));
            head->next = NULL;
            head->v = i;
        }
    }
    printfList(head);
     
    reverse(&head);
    printfList(head);
     
    head = reverse2(head);
    printfList(head);
     
    return 0;
}
 
#endif

测试是可以的。

 
 
 
 
 
 
 
关注公众号"小败日记",搬砖过程遇到的问题,大家一起探讨,资源共享

小败日记公众号

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值