8

#yyds干货盘点# 面试必刷TOP101:反转链表

 1 year ago
source link: https://blog.51cto.com/u_15488507/5511426
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# 面试必刷TOP101:反转链表

原创

97的风 2022-07-25 15:14:39 博主文章分类:面试题 ©著作权

文章标签 链表 代码实现 空间复杂度 文章分类 Java 编程语言 阅读数249

1.简述:

描述

给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。

数据范围: 

要求:空间复杂度  ,时间复杂度  。

如当输入链表{1,2,3}时,

经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。

以上转换过程如下图所示:

#yyds干货盘点# 面试必刷TOP101:反转链表_链表_04

示例1

{1,2,3}
{3,2,1}

示例2

空链表则输出空

2.代码实现:

import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null){
return head;
}
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK