( Leetcode 25 )Reverse Nodes in k-Group

题目:Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For 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


解题思想:

首先题目的意思是说给定一个链表和一个数k,将链表以k个结点为一组进行反转,如果不够k个结点则不进行反转。主要分为以下几步来进行解题:

1.  将链表以k个结点为一组进行拆分,如果够k个结点则进行反转

2.  如果不够k个结点则不进行反转

3.  拼接阶段,将反转后的一小段链表插入到已经操作过的链表中间,如果不够k个结点则不操作。


具体见下面的Java代码(有详细的注释):

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
		if( head == null || head.next == null ){
			return head;
		}
		
		ListNode p = head;
		ListNode pre = null;        //pre 记录上一个半段链表的尾结点
		boolean flag = true;        //为是否是头结点做标记
		while( p != null ){
			ListNode tail = p;     //当前是头,但是反过来就不是头了,成了尾部
			int i;
			for( i = 1; i < k && p != null; ++i ){
				p = p.next;
			}
			
			ListNode nextList = null;
			if( i >= k && p != null ){
				nextList = p.next;
				p.next = null;   //将当前链表的最后一个节点next置为null
				ListNode tempHead = reverse(tail);
				if( flag == true ){  //如果头,进行处理
					head = tempHead;
					flag = false;
					tail.next = nextList;
				}else{             //如果不是头的话
					tail.next = nextList;
					pre.next = tempHead;
				}
			}
			pre = tail;     //记录上一段链表的尾结点
			p = nextList;
		}
		
		return head;
    }
	
	public ListNode reverse( ListNode head ){
		if( head == null || head.next == null ){
			return head;
		}
		ListNode p = head, q = head.next;
		head.next = null;
		while( q != null ){
			ListNode r = q.next;
			q.next = p;
			
			p = q;
			q = r;
		}
		head = p;
		return head;
	}
}


你可能感兴趣的:(java,LeetCode,list,linked)