【leetcode之206. 反转链表】详解
题目描述
[刷题链接](https://leetcode.cn/problems/reverse-linked-list/):
示例1
示例二
这是一道非常经典的面试题,在互联网公司的面试环节面试官考察数据结构相关知识这道题的出现频率很高,也很适合有一定数据结构知识基础的同学尝试,本文将用三种方法解题,希望对你有所帮助。
一、Three-pointer quick solution
错误思路:直接把箭头反过来,即当前cur->next=pre,但是这里有个严重的问题,即cur的下一个节点的位置找不到了
优化思路:使用中间指针tmp接收cur->next,用来记录cur下一个节点的位置
图解:
再改箭头方向
cur->next-pre;
pre和cur指针移动
pre=cur;
cur=tmp;
直到cur指向NULL,循环结束,返回头指针pre
代码实现
struct ListNode* reverseList(struct ListNode* head){
struct ListNode*cur=head;
struct ListNode*pre=NULL;
while(cur)
{
struct ListNode*tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
运行结果
二、Recursive implementation
本方法有些难度,采用最巧妙的递归实现,但是由上一种方法改写而来,有了上一种方法做铺垫,读者朋友们应该能够理解
void reverse(struct ListNode*cur,struct ListNode*pre)
{
if(cur==NULL)
{
return pre;//不断逼近的条件
}
else{
struct ListNode*tmp=cur->next;
cur->next=pre;
return reverse(tmp,cur);
}
}
struct ListNode* reverseList(struct ListNode* head){
reverse(head,NULL);
}
三.Take the element header insertion
此方法更是巧妙
图解:
- 取下第一个元素头插
- 取第二个元素头插
- 取第三个元素头插
4.以此类推,结果
把元素拆下来的操作:next=cur->next;
再把next赋给cur,更新头指针
当cur为空时循环结束
代码如下:
struct ListNode*cur=head;
struct ListNode*next=NULL;
struct ListNode*rhead=NULL;
while(cur)
{
struct ListNode*next=cur->next;
cur->next=rhead;
rhead=cur;
cur=next;
}
return rhead;
这种方法还蛮强
总结
我是麻辣郭德纲,带你提升思维,顺便学习数据结构
这是最近在阅读的书,莫言《酒国》,强烈推荐!!!