##Description:
Reverse a singly linked list.
##问题描述:
反转链表。----in place操作,不要新开空间
给定链表的头结点,得到反转链表的头结点。
##解法一(迭代解法–尾插法)
###思路:直观感觉是将链表的指向全部反向,但是要先用临时结点存储后一结点信息,以免反向后找不到后一节点,迭代之前初始化prev空结点来作为reverse后链表的头结点。每轮更新prev和head向前移动。
Tips:
此类解法比较适合于微操的情况, 比如[a, b)这种前闭后开区间…
###code:
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
if (head == null || head.next == null){
return head;
}
ListNode prev = null;
while (head != null){
//储存后一结点信息
ListNode tmp = head.next;
//指针反向
head.next = prev;
//更新prev和head,均向前移动
prev = head;
head = tmp;
}
return prev;
}
}
##解法二(递归解法)
###思路:
假设链表有N个结点,先递归颠倒最后N-1个结点,然后小心地将原链表中的首结点插入到结果链表的末端
利用递归遍历到链表的尾部
###code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return null;
if(head.next == null) return head;
ListNode second = head.next;
ListNode rest = reverseList(second);
second.next =head;
head.next = null;
return rest;
}
}
K个一组反转链表
核心思路:
将链表区别[a, b)反转, 注意是前闭后开.
思路同非递归单链表反转.
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
//将区间[a, b)进行链表反转
//a.next = reverseKGroup(b, k)
ListNode a = head;
ListNode b = head;
//需要考虑不够长度k的部分, 直接返回head节点
for (int i = 0; i < k; i++) {
if (b == null) {
return head;
}
b = b.next;
}
ListNode newHead = reverse(a, b);
a.next = reverseKGroup(b, k);
return newHead;
}
private ListNode reverse(ListNode a, ListNode b) {
ListNode curr = a;
ListNode pre = null;
while (curr != b) {
ListNode tmp = curr.next;
curr.next = pre;
pre = curr;
curr = tmp;
}
return pre;
}
}