链表k个一组翻转中,对第二部中,翻转k个节点进行优化。和直接反转链表还是有明显区别的。主要是while条件的设置。
翻转链表
public ListNode reverseList(ListNode head) {
ListNode l3 = null;
while(head!=null){
ListNode temp = head.next;
head.next =l3;
l3= head;
head=temp;
}
return l3;
}
翻转k个结点
public static ListNode reverseKGroup(ListNode head, int k) {
if(head == null)
return null;
ListNode temp = new ListNode(0);
temp.next = head;
ListNode pre = temp;
ListNode nhead = pre.next;
while(nhead!=null) {
ListNode tail = pre;
for (int i = 0; i < k; i++) {
tail = tail.next;
if (tail == null)
return temp.next;
}
ListNode nex = tail.next;
ListNode[] reversehead = swapPairs(nhead, tail,k);
ListNode newhead = reversehead[0];
ListNode newtail = reversehead[1];
pre.next = newhead;
newtail.next = nex;
pre = newtail;
nhead = pre.next;
}
return temp.next;
}
public static ListNode[] swapPairs(ListNode head,ListNode tail,int k) {
/*
写法一:
ListNode l3=null;
for(int i=0;i<k;i++){//不要用while(haed!=null),比如12345,3,其对12345倒叙了
ListNode temp = head.next;
head.next = l3;
l3 = head;
head = temp;
}
//找到尾指针
ListNode newtail =l3;
while(k!=1) {
newtail = newtail.next;
k--;
}
return new ListNode[]{l3, newtail};
/*
/*写法二
ListNode prev = tail.next;
ListNode p = head;
while (prev != tail) {
ListNode nex = p.next;
p.next = prev;
prev = p;
p = nex;
}
return new ListNode[]{tail, head};
*/
/*
写法三:优化写法一
不直接操作head 直接返回 tail head 不用和写法一一样去找尾指针了
*/
ListNode l3=tail.next;
ListNode p=head;
// for(int i=0;i<k;i++){
while(l3!=tail){//和for循环等价
ListNode temp = p.next;
p.next = l3;
l3 = p;
p = temp;
}
// ListNode newtail =l3;
// while(k!=1) {
// newtail = newtail.next;
// k--;
// }
return new ListNode[]{tail, head};
}