给你单链表的头节点 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
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
package cn.fansunion.leecode.linkedlist;
/**
* 206.反转链表<br/>
* 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。<br/>
* 力扣
*
* @author [email protected]
*
* 2022-2-18
*/
public class ReverseLinkedList {
/* 输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]*/
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 第1个prev,默认为头结点
ListNode prev = head;
ListNode next = head.next;
// 关键点2:头结点的next需要改为null,不然“循环链表543212345”
head.next = null;
// 关键点1:维护一个尾节点
ListNode foot = head;
while (next != null) {
foot = next;
next = next.next;
foot.next = prev;
prev = foot;
}
return foot;
}
}
package test.leecode.linkedlist;标签:Assert,head,ListNode,3620,next,链表,反转,foot From: https://blog.51cto.com/fansunion/6056783
import org.junit.Assert;
import org.junit.Test;
import cn.fansunion.leecode.linkedlist.ListNode;
import cn.fansunion.leecode.linkedlist.ReverseLinkedList;
/**
* @author [email protected]
*
* 2022-2-23
*/
public class ReverseLinkedListTest {
@Test
public void test() {
ReverseLinkedList list = new ReverseLinkedList();
ListNode node5 = new ListNode(5,null);
ListNode node4 = new ListNode(4,node5);
ListNode node3 = new ListNode(3,node4);
ListNode node2 = new ListNode(2,node3);
ListNode head1 = new ListNode(1,node2);
ListNode foot=list.reverseList(head1);
Assert.assertEquals(5, foot.val);
Assert.assertEquals(4, foot.next.val);
Assert.assertEquals(3, foot.next.next.val);
Assert.assertEquals(2, foot.next.next.next.val);
Assert.assertEquals(1, foot.next.next.next.next.val);
Assert.assertNull(foot.next.next.next.next.next);
}
}