LeetCode 206 Reverse Linked List

Problem:

Reverse a singly linked list.

A linked list can be reversed either iteratively or recursively. Could you implement both?

Summary:

翻转链表。

Analysis:

1. Iterative solution

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head) {
12         ListNode *pre = NULL;
13         
14         while (head != NULL) {
15             ListNode *tmp = head->next;
16             head->next = pre;
17             pre = head;
18             head = tmp;
19         }
20         
21         return pre;
22     }
23 };

 2. Recursive solution

若链表为n1->n2->...->nk-1->nk->nk+1->...->nm->NULL

假设nk+1到nm的部分已翻转:n1->n2->...->nk-1->nk->nk+1<-...<-nm

我们若要使nk+1的next指针指向nk,则我们需要做的是:nk->next->next = nk

需要注意的是需要将n1的next指针指向NULL。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head) {
12         if (head == NULL || head->next == NULL) {
13             return head;
14         }
15         
16         ListNode *tmp = reverseList(head->next);
17         head->next->next = head;
18         head->next = NULL;
19         
20         return tmp;
21     }
22 };

 

Reference: https://leetcode.com/articles/reverse-linked-list/#approach-1-iterative-accepted

转载于:https://www.cnblogs.com/VickyWang/p/6012874.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值