Leetcode_Linked_List --206. Reverse Linked List [easy]

Reverse a singly linked list.
反转一个单链表

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

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

Solution:

Python

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
#运用迭代的方法
class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        oldlist = head   #oldlist定义的是原链表,也就是要反转的链表
        newlist = None   #newlist定义的是新链表,首先初始化为None
        while oldlist != None:   #然后开始遍历旧链表
            temp = oldlist.next   #定义一个暂时的链表存储oldlist.next开头的链表
            oldlist.next = newlist   #将oldlist的头结点作为newlist的头结点添加到newlist中
            newlist = oldlist   #更新新链表的头指针
            oldlist = temp   #将以oldlist.next开头的链表赋给oldlist,这个时候oldlist被更新,其头结点为原oldlist的第二个链表元素
        return newlist   #最终返回新链表
       
 #运用递归的方法
 class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        newlist = self.reverseList(head.next)   #遍历链表,找到链表的最后一个元素,赋给newlist
        head.next.next = head   #将本节点next指针指向本节点的前一个节点
        head.next = None   #将前一个节点指向本节点的next指针断开
        return newlist   #更新newlist
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) {
        if (head == NULL || (head->next) == NULL){
            return head;
        }
        ListNode *newlist = NULL;
        while (head){
            ListNode *temp = (head->next);
            (head->next) = newlist;
            newlist = head;
            head = temp;
        }
        return newlist;
    }
};

// 递归方法
class Solution{
    public:
        ListNode* reverseList(ListNode* head){
            if (!head || !(head->next)){
                return head;
            }
            ListNode* newlist = reverseList((head->next));
            head->next->next = head;
            head->next = NULL;
            return newlist;    
        }
    
};

参考文献:https://blog.csdn.net/fx677588/article/details/72357389

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值