题目描述
输入一个链表,反转链表后,输出新链表的表头。
python:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
new_head = None
while pHead:
next = pHead.next
pHead.next = new_head
new_head = pHead
pHead = next
return new_head
c++:
#include<stdio.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *new_head = NULL;
while(pHead){
ListNode *next = pHead->next;
pHead->next = new_head;
new_head = pHead;
pHead = next;
}
return new_head;
}
};