package test;
//class ListNode{
// int val;
// ListNode next;
// public ListNode(){
//
// }
//
// public ListNode(int val) {
// this.val = val;
// }
//
// public ListNode(int val, ListNode next){
// this.val=val;
// this.next=next;
// }
//}
public class 反转链表II {
public static ListNode createListNode (){
ListNode n1=new ListNode (1);
ListNode n2=new ListNode (2);
ListNode n3=new ListNode (3);
ListNode n4=new ListNode (4);
ListNode n5=new ListNode (5);
ListNode n6=new ListNode (6);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
n5.next=n6;
n6.next=null;
return n1;
}
public static void print( ListNode h){
while(h!=null){
System.out.print(h.val+" ");
h=h.next;
}
System.out.println();
}
//反转链表 头插法
/*
* 在遍历链表时,将当前节点的 next 指针改为指向前一个节点。由于节点没有引用其前一个节点,
* 因此必须事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。
* */
public static ListNode reverseList( ListNode head) {
ListNode p,q;
p=head.next;
head.next=null;
while (p!=null){
q=p;
p=p.next;
q.next=head;
head=q;
}
return head;
}
//递归法
public static ListNode reverse( ListNode head) {
if(head.next == null || head == null )
return head;
ListNode least = reverse(head.next);
//倒数第二个结点移动到最后 ,如此递归下去
System.out.println("=="+head.next.next+"==");
head.next.next = head;
head.next = null;
return least;
}
//反转前n个结点
public static ListNode successor = null; // 后驱节点(第 n + 1 个节点)
public static ListNode reverseN( ListNode head, int n) {
if (n == 1) {
successor = head.next;
return head;
}
// 以 head.next 为起点,需要反转前 n - 1 个节点
ListNode ret = reverseN(head.next, n - 1);
//前一个结点
// System.out.println("=="+head.next.next.data+"==");
head.next.next = head;
head.next = successor; // 将反转后的 head 与后面节点连接
return ret;
}
//反转K个一组的链表
public static ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = head;
for (int i = 0; i < k; i++) {
//剩余数量小于k的话,则不需要反转。
if (tail == null) {
return head;
}
tail = tail.next;
}
// 反转前 k 个元素
ListNode newHead = reverse(head, tail);
//下一轮的开始的地方就是tail
head.next = reverseKGroup(tail, k);
return newHead;
}
/*
左闭又开区间
*/
private static ListNode reverse(ListNode head, ListNode tail) {
ListNode pre = null;
ListNode next = null;
while (head != tail) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static void main(String[] args) {
ListNode h = createListNode();
print(h);
// 反转前3个结点
// System.out.println("反转前n个结点");
// ListNode ListNode = reverseN(h, 2);
// print( ListNode);
// 反转链表
// ListNode reverse = reverse(h);
// print(reverse);
//反转k个一组的链表
ListNode listNode = reverseKGroup(h, 5);
print(listNode);
}
}
反转链表(Java)
最新推荐文章于 2021-09-09 15:35:44 发布