剑指offer:反转链表

问题描述

输入一个链表,反转链表后,输出新链表的表头。

 

c++代码

 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6             val(x), next(NULL) {
 7     }
 8 };*/
 9 class Solution {
10 public:
11     ListNode* ReverseList(ListNode* pHead) {
12         if(pHead == NULL)  return pHead;
13         ListNode *cur = pHead, *nxt, *pre = NULL;
14         while(cur != NULL){
15             nxt = cur->next;
16             cur->next = pre;
17             pre = cur;
18             cur = nxt;
19         }
20         return pre;
21     }
22 };

 

python代码

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 class Solution:
 7     # 返回ListNode
 8     def ReverseList(self, pHead):
 9         # write code here
10         if not pHead:
11             return pHead
12         cur, pre = pHead, None
13         while cur:
14             nxt = cur.next
15             cur.next = pre
16             pre = cur
17             cur = nxt
18         return pre

 

转载于:https://www.cnblogs.com/zyb993963526/p/10481454.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值