LeetCode第25题
/*
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
Only constant extra memory is allowed.
You may not alter the values in the list’s nodes, only nodes itself may be changed.
*/
class ListNode{
int val;
ListNode next;
ListNode(){};
ListNode(int val){this.val=val;}
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class ReverseNodesKGroup{
public static void main(String[] args){
ListNode node1_1 = new ListNode(1);
ListNode node1_2 = new ListNode(2);
ListNode node1_3 = new ListNode(3);
ListNode node1_4 = new ListNode(4);
ListNode node1_5 = new ListNode(5);
node1_1.next = node1_2;
node1_2.next = node1_3;
node1_3.next = node1_4;
node1_4.next = node1_5;
ReverseNodesKGroup snp = new ReverseNodesKGroup();
ListNode result = snp.reverseKGroup(node1_1,3);
while(result != null){
System.out.println(result.val);
result = result.next;
}
}
public ListNode reverseKGroup(ListNode head, int k) {
// head为null、k为1、k的个数大于链表节点数
if (head==null || k==1 || isGreat(head,k)) return head;
// 空节点指向新链表的表头,其本身不存储值
ListNode ret = new ListNode(-1);
ListNode next_head = null;
ListNode cur = null;
ListNode temp = null;
cur = head;
for (int i=0;i<k-1;i++)cur = cur.next;
ret.next = cur;
next_head = cur.next;
cur.next = null;
temp = reverse(head);
for (int i=0;i<k-1;i++)temp = temp.next;
temp.next = next_head;
head = next_head;
// 一个指针指向需要倒置链表的最后一个节点,temp存储子节点最后一个节点的下一个节点,子节点指向null
while(true){
// k不大于节点个数
if (isGreat(head,k)) break;
// 遍历到当前需要转置的最后一个节点
cur = head;
for (int i=0;i<k-1;i++)cur = cur.next;
// temp.next是当前head的前一个节点,现在指向即将转置后子节点的头节点
temp.next = cur;
// cur.next指向null前,保存其下一个节点的位置
next_head = cur.next;
cur.next = null;
// 对子链表进行转置,转置返回的是头节点
temp = reverse(head);
// 转置后尾节点指向剩下节点的头节点,这个操作不能少,否则存在丢失节点信息的问题
for (int i=0;i<k-1;i++)temp = temp.next;
temp.next = next_head;
// 更新头节点
head = next_head;
}
return ret.next;
}
public ListNode reverse(ListNode head) {
ListNode current_head = null;
while (head != null) {
ListNode next = head.next;
head.next = current_head;
current_head = head;
head = next;
}
return current_head;
}
public boolean isGreat(ListNode list, int k){
// 防止空指针异常,list为空就没必要转置
if (list == null) return true;
ListNode temp = list;
for (int i = 0;i<k-1;i++){
temp = temp.next;
if (temp == null) return true;
}
return false;
}
}