Day 14 作业题:反转单链表

46 篇文章 1 订阅

反转单链表检验我们是否能够真正灵活使用它,也是面试频频被问道的一个题目。

例如反转上面单链表的方法之一:

黑色结点的下一个结点现在是空。因此,我们停止这一过程并返回新的头结点 15。

根据以上提示,请补全下面代码:

 

/**
 * 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* pre =NULL;
        ListNode* cur = head;
        ListNode* temp =NULL;
        while (cur!=NULL){
            temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

 

python3 

class ListNode(object):
    def __init__(self,x):
        self.val = x
        self.next = None

class Solution():
    def reverselist(self,head):
        pre =None
        cur =head
        while cur:
            temp =cur.next # 存储下一个结点的值
            cur.next = pre  # 将当前指向下一个结点的值放空
            pre = cur # 将当前的值给到pre
            cur = temp
        return pre

if __name__ == '__main__':
    lists = [2,3,4,5,6,7,8,9]
    head = ListNode(None)
    temp = head
    for item in lists:
        newnode = ListNode(item)
        temp.next = newnode
        temp = newnode
    head = head.next
    result =Solution()
    res = result.reverselist(head)
    while res:
        print(res.val)
        res = res.next

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值