一、题目描述
给定单链表的头节点 head
,请反转链表,并返回反转后的链表的头节点。
示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2] 输出:[2,1]
示例 3:
输入:head = [] 输出:[]
二、题解
解法1(迭代1)
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
ListNode pre = null;
while(head!=null){
ListNode index=head.next;
head.next = pre;
pre = head;
head = index;
}
return pre;
}
}
解法2(迭代2)
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode index = head;
while (index != null) {
ListNode next = index.next;
index.next = pre;
pre = index;
index = next;
}
return prev;
}
}
解法3(头插法)
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode headNode = new ListNode(-1, null);
ListNode p = head;
ListNode r = null;
while(p != null){
r = p.next;
p.next = headNode.next;
headNode.next = p;
p = r;
}
return headNode.next;
}
}
解法4(栈)
class Solution {
public ListNode reverseList(ListNode head) {
if (head==null) return head;
Stack<ListNode> stack = new Stack<>();
while (head!=null){
stack.push(head);
head=head.next;
}
ListNode pre = new ListNode(0);
ListNode cur = pre;
while (!stack.isEmpty()){
cur.next=stack.pop();
cur=cur.next;
}
cur.next=null;
return pre.next;
}
}
解法5 (递归)
class Solution {
public ListNode reverseList(ListNode head) {
// head == null 防止参数Head本身就为null
// haed.next == null,用来让递归停止到第一个结点,就开始返回;
if (head == null || head.next == null) return head;
ListNode node = reverseList(head.next); // 保存最后一个结点;
head.next.next = head; // 翻转指针;
head.next = null; // 置空,递归已保存上一个结点,置空不影响连接
return node; // 返回最后一个结点
}
}
测试方法
public class Test {
public static void main(String[] args) {
// 创建链表节点
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
// 调用翻转链表方法
Solution solution = new Solution();
ListNode reversedHead = solution.reverseList(node1);
// 打印翻转后的链表节点值
while (reversedHead != null) {
System.out.print(reversedHead.value + " ");
reversedHead = reversedHead.next;
}
}
}