「这是我参与2022首次更文挑战的第36天,活动详情查看:2022首次更文挑战」
前言
笔者除了大学时期选修过《算法设计与分析》和《数据结构》还是浑浑噩噩度过的(当时觉得和编程没多大关系),其他时间对算法接触也比较少,但是随着开发时间变长对一些底层代码/处理机制有所接触越发觉得算法的重要性,所以决定开始系统的学习(主要是刷力扣上的题目)和整理,也希望还没开始学习的人尽早开始。
系列文章收录《算法》专栏中。
问题描述
给定单链表的头节点 head ,请反转链表,并返回反转后的链表的头节点。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是 [0, 5000]
- -5000 <= Node.val <= 5000
剖析
这道题比较简单,把链表的指针掉个头就行。如下:
1->2->3->null改成null<-1->2->3
代码
public class LinkList {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode reverseList(ListNode head) {
ListNode curr = head;
ListNode prev = null;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
为了方便测试可以使用以下代码:
import java.util.LinkedList;
/**
* description :
*
* @author : wanghaifeng
* date : 2022/1/19
*/
public class LinkList {
/**
* 头
*/
private ListNode first;
/**
* 当前最后一个
*/
private ListNode last;
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
/**
* 尾插
*
* @param i
*/
public void putTail(Integer i) {
ListNode l = last;
ListNode newNode = new ListNode(i, null);
last = newNode;
if (l == null) {
first = newNode;
} else {
l.next = newNode;
}
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer("[");
if (first != null) {
sb.append(first.val);
ListNode nextNode = first.next;
while (nextNode != null) {
sb.append(", " + nextNode.val);
nextNode = nextNode.next;
}
sb.append("]");
return sb.toString();
}
return "[]";
}
public ListNode getLast() {
return last;
}
public ListNode reverseList(ListNode head) {
ListNode curr = head;
ListNode prev = null;
last = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
first = prev;
return prev;
}
public static void main(String[] args) {
LinkList linkList = new LinkList();
for (int i = 1; i < 6; i++) {
linkList.putTail(i);
}
System.out.println(linkList);
linkList.reverseList(linkList.first);
System.out.println(linkList);
// LinkedList<Integer> linkedList = new LinkedList<>();
// for (int i = 1; i < 6; i++) {
// linkedList.add(i);
// }
// System.out.println(linkedList.toString());
}
}