博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Reverse Nodes in k-Group
阅读量:4074 次
发布时间:2019-05-25

本文共 1342 字,大约阅读时间需要 4 分钟。

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

Java代码:

public class Test_78 {	public static ListNode reverseKGroup(ListNode head, int k) {		ListNode tmp = head;		for (int i = 0; i < k; i++) {			if (null == tmp) {				return head;			} else {				tmp = tmp.next;			}		}//将链表根据基数k分隔,tmp指向下一k个节点的第一个		ListNode tmp_2 = head;		for (int i = 0; i < k - 1; i++)//获得基数k中的最后一个节点			tmp_2 = tmp_2.next;		tmp_2.next = head;//收尾相连		ListNode tmp_3=null;				int count =k-2;		while(count >0)	//实现前k个节点的		{			count--;		tmp_3 = head.next;		head.next = head.next.next;		tmp_3.next = tmp_2.next;		tmp_2.next=tmp_3;		}				head.next = reverseKGroup(tmp, k);		head = tmp_2;		return head;	}	public static void main(String[] arqs) {		ListNode head = new ListNode(1);		head.next = new ListNode(2);		head.next.next = new ListNode(3);				head = reverseKGroup(head, 3);		while(null != head){			System.out.println(head.val);			head = head.next;		}	}}

 

转载地址:http://qpuni.baihongyu.com/

你可能感兴趣的文章
React Native(四):布局(使用Flexbox)
查看>>
React Native(七):Android双击Back键退出应用
查看>>
Android自定义apk名称、版本号自增
查看>>
【剑指offer】q50:树中结点的最近祖先
查看>>
二叉树的非递归遍历
查看>>
【leetcode】Reorder List (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>
如何成为编程高手
查看>>
本科生的编程水平到底有多高
查看>>
Solr及Spring-Data-Solr入门学习
查看>>
python_time模块
查看>>
python_configparser(解析ini)
查看>>
selenium学习资料
查看>>
从mysql中 导出/导入表及数据
查看>>
HQL语句大全(转)
查看>>
几个常用的Javascript字符串处理函数 spilt(),join(),substring()和indexof()
查看>>
javascript传参字符串 与引号的嵌套调用
查看>>