File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -371,6 +371,45 @@ func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? {
371
371
}
372
372
```
373
373
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
+
374
413
-----------------------
375
414
* 作者微信:[ 程序员Carl] ( https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw )
376
415
* B站视频:[ 代码随想录] ( https://space.bilibili.com/525438321 )
You can’t perform that action at this time.
0 commit comments