题目描述
输入一个链表,反转链表后,输出新链表的表头。
C++实现:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *c = NULL, *p = NULL, *t = NULL;
c = pHead;
t = pHead;
while(t)
{
t = t -> next;
c -> next = p;
p = c;
c = t;
}
return p;
}
};
Python实现:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead == None or pHead.next == None:
return pHead;
c = pHead
t = pHead
p = None
while(t):
t = t.next
c.next = p
p = c
c = t
return p