https://leetcode-cn.com/problems/reverse-linked-list/
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
https://www.bilibili.com/video/BV1KZ4y157Up?from=search&seid=7613549620764321902
问题分析:这道算法题实际上就是如何让后一个节点指向前一个节点。定义三个指针,pre, cur,tmp,tmp节点主要是为了在断裂前,保存当前节点的后驱节点,防止链表断裂
package linkedlist;
class ListNode{
int val;
ListNode next;
ListNode(){}
public ListNode(int val){
this.val = val;
}
public ListNode(int val, ListNode next){this.val = val; this.next = next;}
}
public class ReverseList {
public static void main(String[] args) {
ListNode listNode = new ListNode(3);
ListNode listNode1 = new ListNode(5);
ListNode listNode2 = new ListNode(6);
ListNode listNode3 = new ListNode(2);
listNode.next = listNode1;
listNode1.next = listNode2;
listNode2.next = listNode3;
ListNode h = listNode;
while (h!=null){
System.out.print(h.val+" ");
h = h.next;
}
ListNode pre = reverseList(listNode);
System.out.println("-------翻转后的链表");
while (pre!=null){
System.out.print(pre.val+" ");
pre = pre.next;
}
}
public static ListNode reverseList(ListNode head){
//设置三个临时指针,pre,cur,tmp
//tmp主要是为了保证链表不断裂,在后驱节点指向前驱节点前记录当前节点的后驱节点
ListNode pre = null;
ListNode cur = head;
ListNode tmp;
while (cur!=null){//循环以下过程,直至当前节点为空,反转结束,返回pre指针
tmp = cur.next;//在断裂前记录当前节点的后驱节点
cur.next = pre;//断裂,使得当前节点指向前驱节点,进行翻转
pre = cur;//pre往后移
cur = tmp;//cur往后移
}
return pre;
}
}