leetcode Title 25. K flip list in groups

topic

Give you a list, each k nodes to flip a group, you return to the list after the flip.

k is a positive integer that is less than or equal to the length of the list.

If the total number of nodes is not an integral multiple of k, then set the last remaining node original order.

Examples

Given this list: 1-> 2-> 3-> 4-> 5

When k = 2, it should be returned: 2-> 1-> 4-> 3-> 5

When k = 3, should be returned: 3-> 2-> 1-> 4-> 5

General idea

Here are two approaches, the first stack is used for each cycle k into a node, followed by an inverted stack connected implemented, but note problems predecessor nodes connected with comments in the code, the following code is only a first wording species.
The second is also a time to traverse k nodes, but does not use the stack. Storage nodes k k nodes and predecessor nodes in the last tail node and then the next and so connected to the precursor node of the end node, too, to be noted that if the chain length is a multiple of k problem.

Code

public class problem25 {
	 //Definition for singly-linked list.
	 public static class ListNode {
	     int val;
	     ListNode next;
	     ListNode(int x) { val = x; }
	 }
	 public ListNode reverseKGroup(ListNode head, int k) {
		 if(k==1) return head;//特判
		 
		 Stack<ListNode> st=new Stack<ListNode>();
		 
		 ListNode pre=new ListNode(0);//额外的头节点,用于连接翻转
		 ListNode re=pre;//保存结果
		 int i=0;
		 
		 while(head!=null){
			 i=0;
			 
			 //前驱节点连接
			 pre.next=head;
			 
			 //依此将k个节点入栈
			 for(i=0;i<k&&head!=null;i++){
				 st.add(head);
				 head=head.next;
			 }
			 
			 if(i!=k) break;
			 
			 //依此出栈,并连接节点,实现翻转
			 while(st.size()!=0){
				 pre.next=st.pop();
				 pre=pre.next;
			 }
			 
		 }
		 
		//判断上述循环退出的情况,如果链表长度是k的倍数,那么最后一个节点还指向倒数第二个,会形成死循环
		 if(i==k) pre.next=null;
		 
		 return re.next;
     }
	 
	 public static void main(String[] args) {
			ListNode a=new ListNode(1);
			a.next=new ListNode(2);
			a.next.next=new ListNode(3);
			a.next.next.next=new ListNode(4);
			a.next.next.next.next=new ListNode(5);
			
			problem25 pro=new problem25();
			ListNode re=pro.reverseKGroup(a, 2);
			while(re!=null){
				System.out.println(re.val);
				re=re.next;
			}
		}
}
2
1
4
3
5

Published 15 original articles · won praise 0 · Views 177

Guess you like

Origin blog.csdn.net/qq_36360463/article/details/104018245