Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8f1fe3c

Browse files
添加 0206.翻转链表.md C语言版本
1 parent 5cb33c3 commit 8f1fe3c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

problems/0206.翻转链表.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,45 @@ func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? {
371371
}
372372
```
373373

374+
C:
375+
双指针法:
376+
```c
377+
struct ListNode* reverseList(struct ListNode* head){
378+
//保存cur的下一个结点
379+
struct ListNode* temp;
380+
//pre指针指向前一个当前结点的前一个结点
381+
struct ListNode* pre = NULL;
382+
//用head代替cur,也可以再定义一个cur结点指向head。
383+
while(head) {
384+
//保存下一个结点的位置
385+
temp = head->next;
386+
//翻转操作
387+
head->next = pre;
388+
//更新结点
389+
pre = head;
390+
head = temp;
391+
}
392+
return pre;
393+
}
394+
```
395+
396+
递归法:
397+
```c
398+
struct ListNode* reverse(struct ListNode* pre, struct ListNode* cur) {
399+
if(!cur)
400+
return pre;
401+
struct ListNode* temp = cur->next;
402+
cur->next = pre;
403+
//将cur作为pre传入下一层
404+
//将temp作为cur传入下一层,改变其指针指向当前cur
405+
return reverse(cur, temp);
406+
}
407+
408+
struct ListNode* reverseList(struct ListNode* head){
409+
return reverse(NULL, head);
410+
}
411+
```
412+
374413
-----------------------
375414
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
376415
* B站视频:[代码随想录](https://space.bilibili.com/525438321)

0 commit comments

Comments
 (0)