206.反转链表
链接:206.反转链表
难度:Easy
标签:递归、链表
简介:反转一个单链表。
题解 1 - java
- 编辑时间:2020-02-13
- 内存消耗:37.3MB
- 编程语言:java
- 解法介绍:创建链表,循环头部插入。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode newHead=null;
while(head!=null) {
ListNode tmp=head.next;
head.next=newHead;
newHead=head;
head=tmp;
}
return newHead;
}
}
题解 2 - cpp
- 编辑时间:2022-03-03
- 执行用时:8ms
- 内存消耗:8.1MB
- 编程语言:cpp
- 解法介绍:双指针。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return head;
ListNode *newHead = nullptr, *tmp;
while (head) {
tmp = head->next;
head->next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
};
题解 3 - c
- 编辑时间:2021-11-19
- 执行用时:4ms
- 内存消耗:6.6MB
- 编程语言:c
- 解法介绍:递归。
struct ListNode* reverseList(struct ListNode* head){
if (head == NULL || head->next == NULL) return head;
struct ListNode *next = head->next;
struct ListNode *reverse_head = reverseList(next);
next->next = head;
head->next = NULL;
return reverse_head;
}
题解 4 - typescript
- 编辑时间:2021-03-06
- 执行用时:100ms
- 内存消耗:40MB
- 编程语言:typescript
- 解法介绍:递归。
function reverseList(head: ListNode | null): ListNode | null {
if (head === null || head.next === null) return head;
const nextList = reverseList(head.next);
head.next.next = head;
head.next = null;
return nextList;
}