Java反转链表
要求:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
对于链表的定义如下:
Definition for singly-linked list.
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;
}
}
1 迭代解法
不断调整节点的next的指向,让头结点指向null,第二个节点指向第一个节点,第二个节点指向第一个节点,依次类推即可。
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
2 递归解法
- 大问题拆分成子问题。
- 子问题求解方式和大问题一样。
- 存在最小子问题。
递归地调整节点的指向。
public ListNode reverseList(ListNode head) {
// 1. 递归终止条件
if (head == null || head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
3 循环反转(假反转,只是值的交换)
从头结点开始,将头结点的值交换到最后一个节点,然后再将新的头结点的值交换到倒数第二个节点,不断循环,直至所有值都完成交换。
class Solution {
public ListNode reverseList(ListNode head) {
int n = 0; //记录链表长度
ListNode pre = head;
//求链表的长度
while(pre!=null){
++n;
pre = pre.next;
}
//从头结点开始交换,需要交换n-1次
for(int i=n-1;i>0;--i){
pre = head;
//每个节点需要交换i次
for(int j=0;j<i&&pre!=null;++j){
int val = pre.val;
pre.val = pre.next.val;
pre.next.val = val;
pre = pre.next;
}
}
return head;
}
}
1和2可以观看视频讲解讲解