要求
- 时间限制:1秒
- 空间限制:32768K
- 热度指数:394494
- 本题知识点: 链表
题目描述
输入一个链表,反转链表后,输出新链表的表头。
思路
思路一:辅助空间
该方法需要构造一个辅助数组,不推荐使用。时间复杂度为O(n)O(n)O(n),空间复杂度为O(n)O(n)O(n)。
C++实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* p = pHead;
int count = 0;
while (p){
count++;
p = p->next;
}
int a[count];
p = pHead;
for (int i=count-1; i>=0; i--){
a[i] = p->val;
p = p->next;
}
p = pHead;
for (int i=0; i<count; i++){
p->val = a[i];
p = p->next;
}
return pHead;
}
};
- 运行时间:2ms
- 占用内存:480k
思路二: 头插法实现
每次从旧链表中取出第一个结点插入到新链表的头部。这种方法的时间复杂度为O(n)O(n)O(n),空间复杂度为O(1)O(1)O(1)。
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
newHead = ListNode(0)
while pHead:
# 保存旧链表的头结点
p = pHead
pHead = pHead.next
# 将上述保存的头结点插入到新链表的头结点之后
temp = newHead.next
newHead.next = p
newHead.next.next = temp
return newHead.next
- 运行时间:33ms
- 占用内存:5864k
C++实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode newHead(0);
ListNode* temp_old = pHead;
ListNode* temp_new = &newHead;
while (pHead){
// 取出旧链表当前的头结点
temp_old = pHead;
pHead = pHead->next;
// 将取出的头结点使用头插法插入新链表
temp_new = newHead.next;
newHead.next = temp_old;
newHead.next->next = temp_new;
}
return newHead.next;
}
};
- 运行时间:4ms
- 占用内存:472k