反转整个链表
- 递归法反转整个链表
- 迭代法反转整个链表
1.递归法反转整个链表
206. 反转链表
class Solution {
public ListNode reverseList(ListNode head) {
//使用递归方法反转链表,重点是注意递归函数的定义
//递归函数定义:输入一个头节点,返回反转后的结果
//首先确定base case
if(head == null || head.next == null){
return head;
}
ListNode last = reverseList(head.next);
head.next.next = head;
head .next = null;
return last;
}
}
2.迭代法反转整个链表
public ListNode reverseN(ListNode head,ListNode b){
//反转以[head,b)区间内的链表,首先会反转整个链表
//以迭代法反转整个链表
ListNode pre = null;
ListNode cur = head , nxt = cur;
while(cur != b){
//当cur!=null条件时,是反转整个链表
nxt = cur.next;
cur.next = pre ;
pre = cur ;
cur = nxt;
}
return pre;
}
反转以head节点开头,长度为n的链表
- 递归法
- 迭代法
1.递归法
92. 反转链表 II
主要是用到了递归的方法,并且将反转后的节点与后面将要反转的节点连接起来
//记录翻转后的后驱节点
ListNode tra = null;
//首先定义一个函数,reverseN(),主要目的是输入一个head 和n,返回以head为头节点,长度为n的反转后的链表
public ListNode reverseN(ListNode head , int n ) {
//求前n个节点的链表的反转
if(n == 1){
//记录n+_1个节点
tra = head.next;
return head;
}
//以head.next 为起点,翻转前n-1 个节点
ListNode last = reverseN(head.next,n-1);
head.next.next = head;
//让反转后的head节点和后面的节点连接起来
head.next = tra;
return last;
}
2.迭代法
public ListNode reverseN(ListNode head,ListNode b){
//反转以[head,b)区间内的链表,首先会反转整个链表
//以迭代法反转整个链表
ListNode pre = null;
ListNode cur = head , nxt = cur;
while(cur != b){
//当cur!=null条件时,是反转整个链表
nxt = cur.next;
cur.next = pre ;
pre = cur ;
cur = nxt;
}
return pre;
}
反转某个区间[a,b)上的链表
- 递归法
- 迭代法
- 递归法
92. 反转链表 II
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
//使用递归法求解
if(left == 1){
return reverseN(head,right);
}
head.next = reverseBetween(head.next,left-1,right-1);
return head;
}
//记录翻转后的后驱节点
ListNode tra = null;
//首先定义一个函数,reverseN(),主要目的是输入一个head 和n,返回以head为头节点,长度为n的反转后的链表
public ListNode reverseN(ListNode head , int n ) {
//求前n个节点的链表的反转
if(n == 1){
//记录n+_1个节点
tra = head.next;
return head;
}
//以head.next 为起点,翻转前n-1 个节点
ListNode last = reverseN(head.next,n-1);
head.next.next = head;
//让反转后的head节点和后面的节点连接起来
head.next = tra;
return last;
}
}
- 迭代法
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) {
//使用迭代法反转链表,首先要会使用迭代法反转以a为开头的链表
//现在会使用反转一个区间[a,b)内的链表
//接着想办法实现满足题意
if (head == null){
return null;
}
ListNode a,b;
a = b = head;
for(int i = 0; i < k;i++){
if(b == null){
//不满足k个,不需要反转
return head;
}
b = b.next;
}
ListNode newHead = reverseN(a,b);
//递归反转后序的链表,并且连接起来
a.next = reverseKGroup(b,k);
return newHead;
}
public ListNode reverseN(ListNode head,ListNode b){
//反转以[head,b)区间内的链表,首先会反转整个链表
//以迭代法反转整个链表
ListNode pre = null;
ListNode cur = head , nxt = cur;
while(cur != b){
//当cur!=null条件时,是反转整个链表
nxt = cur.next;
cur.next = pre ;
pre = cur ;
cur = nxt;
}
return pre;
}
}