反转链表
题目描述
https://leetcode.cn/problems/reverse-linked-list/
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例一:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
解题思路
迭代法
如果链表为空,或者链表只有一个结点,那么就可以直接返回头结点,因为此时不需要进行反转。否则的话,我们就通过迭代来进行反转,需要定义几个变量,pre,curr,next,对这几个结点来进行操作。
class Solution {
public ListNode reverseList(ListNode head) {
//如果链表为空,或者链表只有一个节点,则直接返回头结点
if(head==null || head.next==null) return head;
ListNode pre=null;
ListNode curr=head;
while(curr!=null){
ListNode temp=curr.next;
curr.next=pre;
pre=curr;
curr=temp;
}
return pre;
}
}
递归法
一文读懂链表反转(迭代法和递归法) - 你是风儿 - 博客园
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
return recur(head,pre);
}
/**
反转两个结点
*/
private ListNode recur(ListNode curr,ListNode pre){
//终止条件
if(curr==null) return pre;
//递归后继结点
ListNode res=recur(curr.next,curr);
//修改节点引用指向
curr.next=pre;
//返回链表头结点
return res;
}
}
92. 反转链表 II
题目描述
解题思路
/**
* 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; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if(head==null || head.next==null) return head;
ListNode dummyNode=new ListNode(-1,head);
ListNode p=dummyNode;
//我们先找到left位置的前一个节点p
int i=0;
while(i<left-1){
i++;
p=p.next;
}
//这个时候先反转left到right位置的链表节点
ListNode cur=p.next;
ListNode pre=null;
for(i=left;i<=right;i++){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
//此时cur指向的反转链表的下一个节点
p.next.next=cur;
p.next=pre;
return dummyNode.next;
}
}
25. K 个一组翻转链表
题目描述
解题思路
/**
* 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; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
//先求出链表长度
int n=0;
for(ListNode cur=head;cur!=null;cur=cur.next){
n++;
}
//链表剩余长度>=k才需要进行反转
ListNode dummyNode=new ListNode(-1,head);
ListNode p=dummyNode;
ListNode cur=head;
for(;n>=k;n-=k){
//反转这k个节点
ListNode pre=null;
for(int i=1;i<=k;i++){
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
ListNode temp=p.next;
p.next.next=cur;
p.next=pre;
p=temp;
}
return dummyNode.next;
}
}