*LeetCode--25. Reverse Nodes in k-Group (按k一组翻转链表)
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为一组旋转。如1->2->3->4->5, 且k=2,则旋转后 2->1->4->3->5。 若k=3,则旋转后3->2->1->4->5
详细见:http://www.2cto.com/kf/201412/361798.html
方法:每一组的所有元素按照头插法插入,然后将后面的连接到前面的链表上。
1、先 求出链表总的元素个数temp
2、创建一个头结点result,用来指向result->next=head,并保存头节点reverhead=result;
3、 用temp和k的值比较 while(k<=temp) 当k小于等于temp时就进行逆置操作
4、设置部分逆置长度 ,令 t=k , while(t>0) 进行部分逆置
5、temp=temp-k 最后返回 reverhead->next
public static ListNode reverseKGroup(ListNode head, int k) { ListNode pre =head; ListNode q = head; ListNode result = new ListNode(0); //存放结果 result.next = head; ListNode reshead= result; //指向结果的头部 int temp = 0; //存放节点总数 while(q!=null){ //计算节点总数 ++temp; q=q.next; } q = head; //q存放要翻转的节点,pre指示q前面的节点 int t; //每组翻转的次数 while(k<=temp){ t = k; ListNode remark = q; while(t>0){ pre = q ; q = q.next; pre.next = result.next; //带头结点的头插法 result.next = pre; t--; } remark.next = q; //将每一部分连接起来 result = remark; //改变result,指向部分逆置的最后一个节点(就是下一次头插法的头节点) temp -=k; } return reshead.next; }

浙公网安备 33010602011771号