算法之单链表翻转

问题描述

实现一个单链表的翻转。例如给定链表如下:

1->2->3->4

翻转后,结果为:

4->3->2->1

实现方式

//翻转指针
//实现思路:本人第一思路如此(比较笨拙)
//三指针,分情况讨论的(流汗,估计面试的话,一轮游的水平)。
int reverse(struct node** node){
    
    struct node* tmp = (*node)->next;
    
    struct node* last = NULL;
    struct node* pre = tmp;
    if(tmp->next){
        tmp = tmp->next;
    }
    if(tmp->next->next){
        last = tmp->next;
    }
    if(tmp==NULL){
        *node = pre;
        return 0;
    }
    if(last==NULL){
        tmp->next = pre;
        pre->next = NULL;
        *node = tmp;
        return 0;
    }
   
    pre->next = NULL;
    //直接移动即可
    while (last) {
        tmp->next = pre;
        pre = tmp;
        tmp = last;
        last = last->next;
    }
    
    if(tmp!=NULL){
        tmp->next = pre;
    }
   (*node)->next = tmp;
   return 0;
       
}

实现方式二:
	翻转的本质:就是记录下一个元素的指针,将当前元素指向上一个元素即可
int reverse2(struct node** node){
    struct node* head = *node;
    if(head == NULL){
        return 0;
    }
    //记录上一个元素
    struct node* pre = NULL;
    //记录当前一个元素
    struct node* p = head->next;
    struct node* h =NULL;
    while (p) {
        h = p;
        struct node* tmp = p->next;
        p->next = pre;
        pre = p;
        p = tmp;
    }
    return 0;
}
另外附上C语言实现链表、打印链表的工具类
#include <stdio.h>

//声明链表结点
struct node{
    int value;
    struct node * next;
};

extern int make(struct node** node,int* org,int len);
//构造一个链表
int make(struct node** node,int* org,int len){
    if(len<=0){
        return -1;
    }
    //构造头结点(并且从第二个结点开始放数据)
    *node = (struct node*)malloc(sizeof(struct node));
    struct node* tmp = *node;
    int i = 0;
    while (i<len) {
        tmp->next = (struct node*)malloc(sizeof(struct node));
        tmp->next->value = org[i];
        tmp->next->next = NULL;
        tmp = tmp->next;
        i++;
    }
    return 0;
}

//打印一个链表
void print(struct node* node){
    struct node* tmp = node->next;
    while (tmp) {
        printf(" %d ", tmp->value);
        tmp = tmp->next;
    }
    printf("\n");
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值