标签:null -- 否则 引用 节点 方法 return while 一个
static class ListNode {
public int val;
public ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
new _0327_旋转链表().rotateRight(node1,2);
}
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
// 解题思路 : 不断地拿到最后一个节点进行头插入
ListNode temp = head;
while (k-- > 0) {
ListNode[] res = lastNode(temp);
head = res[1];
head = new ListNode(res[0].val, head);
temp = head;
}
return head;
}
private ListNode[] lastNode(ListNode head) {
ListNode temp = head;
ListNode[] res = new ListNode[2];
while (temp != null && temp.next != null) {
if (temp.next.next == null) {
//存储最后一位节点数据
res[0] = temp.next;
temp.next = null;
//删除最后一个节点链表的头结点;
res[1] = head;
break;
}
temp = temp.next;
}
return res;
}
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
ListNode res = head;
int length = getListNodeLength(head);
head = circleListNode(head);
// boolean circle = isCircle(head);
return getResListNode(head, k, length);
}
/**
* 返回最终解结果
*
* @param head
* @param k
* @param length
* @return
*/
private ListNode getResListNode(ListNode head, int k, int length) {
// 防止 k > length 的出现
int temp = length - k % length;
while (temp-- > 0) {
head = head.next;
}
//移动头指针
ListNode res = head;
while (length-- != 1) {
res = res.next;
}
//截断环形链表
res.next = null;
return head;
}
/**
* 将链表变成环形链表
*
* @return
*/
private ListNode circleListNode(ListNode head) {
ListNode res = head;
while (res != null) {
if (res.next == null) {
res.next = head;
//返回环形链表
return res.next;
}
res = res.next;
}
return null;
}
/**
* 检查链表成环是否成功
*
* @param node
* @return
*/
private boolean isCircle(ListNode node) {
ListNode quick = node;
ListNode low = node;
while (quick != null && quick.next != null) {
low = low.next;
quick = quick.next.next;
if (quick == low) {
return true;
}
}
return false;
}
/**
* 获取链表长度
*
* @param head
* @return
*/
private int getListNodeLength(ListNode head) {
// 这个地方一个要添加一个指针,否则引用传递会改变链表的位置
ListNode temp = head;
int length = 1;
while (temp.next != null) {
length++;
temp = temp.next;
}
return length;
}
标签:null -- 否则 引用 节点 方法 return while 一个
原文地址:https://www.cnblogs.com/init-qiancheng/p/14585062.html