[Leetcode206]反转链表

反转一个单链表。你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

我觉得这道题微妙的地方在于考查递归的思想。目前只用迭代的方法做出了,递归还没想明白,日后补上。

python(迭代):

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head.next == None:
            return head
        return 

C++(迭代): 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* end = NULL;
        while(head){
            ListNode* Next = head->next;
            head->next = end;
            end = head;
            if(Next) head = Next;
            else break;
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/83048143