一、单链表反转。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解答
(1) 非递归版本
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
(2) 递归版本
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
二、单链表中部分反转
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode cur = dummyHead;
for (int i = 1; i < m; i++) {
cur = cur.next;
}
ListNode tail = cur.next;
ListNode pre = null;
for (int i = m; i <= n; i++) {
ListNode next = tail.next;
tail.next = pre;
pre = tail;
tail = next;
}
cur.next.next = tail;
cur.next = pre;
return dummyHead.next;
}
}
三、K个一组反转链表
给你一个链表,每k个节点一组进行翻转,请你返回翻转后的链表。
k是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是k的整数倍,那么请将最后剩余的节点保持原有顺序。
示例:
给你这个链表:1->2->3->4->5
当k= 2 时,应当返回: 2->1->4->3->5
当k= 3 时,应当返回: 3->2->1->4->5
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null)
return head;
ListNode tail = head;
for (int i = 0; i < k; i++) {
if (tail == null)
return head;
tail = tail.next;
}
ListNode newHead = reverse(head,tail);
head.next = reverseKGroup(tail,k);
return newHead;
}
private ListNode reverse(ListNode head, ListNode tail) {
ListNode pre = null;
ListNode cur = head;
while (cur != tail) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}