206. Reverse Linked List(Linked List-Easy)

本文介绍了一种反转单链表的算法实现,提供了C语言和Python两种版本的代码示例,包括迭代和递归两种方法。

转载请注明作者和出处: http://blog.csdn.net/c406495762

Reverse a singly linked list.

Hint:

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

题目:反转单链表,可以使用迭代或者递归的方法。

    迭代的方法,简单说下就是:当迭代到最深层,返回的时候cur的地址和new_head的地址是一致的。操作cur就相当于操作new_head。head->next = NULL 就是将已经返回后的值丢掉。

Language:C

iteratively :

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* pre = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode* cur = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode* temp = (struct ListNode *)malloc(sizeof(struct ListNode));
    if(head == NULL || head->next == NULL){
        return head;
    }
    pre = head;
    cur = head->next;
    pre->next = NULL;
    while(cur != NULL){
        temp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = temp;
    }
    return pre;
}

recursively:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* cur = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode* new_head = (struct ListNode *)malloc(sizeof(struct ListNode));
    if(head == NULL || head->next == NULL){
        return head;
    }
//迭代到最深层,返回的时候cur的地址和new_head的地址是一致的。操作cur就相当于操作new_head。head->next = NULL 就是将已经返回后的值丢掉。
    cur = head->next;
    new_head = reverseList(cur);
    head->next = NULL;
    cur->next = head;
    return new_head;
}

Language : 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
        """
        pre = None
        while head:
            cur = head
            head = head.next
            cur.next = pre
            pre = cur
        return pre          

LeetCode题目汇总: https://github.com/Jack-Cherish/LeetCode

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jack-Cui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值