mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 13:00:22 +08:00
添加 0206.翻转链表.md C语言版本
This commit is contained in:
@ -371,6 +371,45 @@ func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
C:
|
||||||
|
双指针法:
|
||||||
|
```c
|
||||||
|
struct ListNode* reverseList(struct ListNode* head){
|
||||||
|
//保存cur的下一个结点
|
||||||
|
struct ListNode* temp;
|
||||||
|
//pre指针指向前一个当前结点的前一个结点
|
||||||
|
struct ListNode* pre = NULL;
|
||||||
|
//用head代替cur,也可以再定义一个cur结点指向head。
|
||||||
|
while(head) {
|
||||||
|
//保存下一个结点的位置
|
||||||
|
temp = head->next;
|
||||||
|
//翻转操作
|
||||||
|
head->next = pre;
|
||||||
|
//更新结点
|
||||||
|
pre = head;
|
||||||
|
head = temp;
|
||||||
|
}
|
||||||
|
return pre;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
递归法:
|
||||||
|
```c
|
||||||
|
struct ListNode* reverse(struct ListNode* pre, struct ListNode* cur) {
|
||||||
|
if(!cur)
|
||||||
|
return pre;
|
||||||
|
struct ListNode* temp = cur->next;
|
||||||
|
cur->next = pre;
|
||||||
|
//将cur作为pre传入下一层
|
||||||
|
//将temp作为cur传入下一层,改变其指针指向当前cur
|
||||||
|
return reverse(cur, temp);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ListNode* reverseList(struct ListNode* head){
|
||||||
|
return reverse(NULL, head);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
|
Reference in New Issue
Block a user