翻转链表II

xiaoxiao2021-02-28  112

翻转链表中第m个节点到第n个节点的部分  注意事项 m,n满足1 ≤ m ≤ n ≤ 链表长度 样例

给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null

import java.util.Scanner; /** * 翻转链表中第m个节点到第n个节点的部分 注意事项 m,n满足1 ≤ m ≤ n ≤ 链表长度 样例 给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null * * @author Dell * */ public class Test36 { public static ListNode reverseBetween(ListNode head, int m, int n) { if(head==null||head.next==null||m==n) return head; ListNode temp1=new ListNode(-1); temp1.next=head; ListNode p=find1(temp1,m); ListNode end=find2(temp1,n); ListNode start=p.next; p.next=null; ListNode q=end.next; end.next=null; ListNode temp=new ListNode(-1); ListNode r=start; while(start!=null) { r=start; start=start.next; r.next=temp.next; temp.next=r; } p.next=temp.next; ListNode t=temp.next; ListNode x=null; while(t!=null) { if(t.next==null) x=t; t=t.next; } x.next=q; return temp1.next; } public static ListNode find1(ListNode head,int k) { ListNode p=head; int count=1; while(p!=null&&count<k) { p=p.next; count++; } return p; } public static ListNode find2(ListNode head,int k) { ListNode p=head.next; int count=1; while(p!=null&&count<k) { p=p.next; count++; } return p; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ListNode list=new ListNode(-1); ListNode p=list; for(int i=0;i<n;i++) { ListNode temp=new ListNode(sc.nextInt()); p.next=temp; p=p.next; } int m=sc.nextInt(); int k=sc.nextInt(); ListNode result=reverseBetween(list.next,m,k); ListNode q=result; while(q!=null) { System.out.print(q.val+" "); q=q.next; } } }

转载请注明原文地址: https://www.6miu.com/read-59842.html

最新回复(0)