class Solution { public ListNode swapNodes(ListNode head, int k) { int n=0; ListNode c=head; while(c!=null){ n++; c=c.next; } //卡住的原因:特殊情况没有考虑全面 //1.链表只有一个节点时 //2.正数第k个节点和倒数第k个节点是同一个节点时 if(n==1 || (n-k)==(k-1)) return head; //倒数第k个节点 n-k int temp1=0; int max1=Math.max(n-k,k-1); int min1=Math.min(n-k,k-1); ListNode cur=head; ListNode temp=null; for(int i=0;i143. 重排链表 class Solution { public void reorderList(ListNode head) { //自己做时特殊情况忘记了考虑 if(head==null || head.next==null ||head.next.next==null) return; //找中点时采用快慢指针的办法 //找中点,链表分成两个 ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } ListNode newHead = slow.next; slow.next = null; ListNode new1=reverse(newHead); ListNode x=head; //采用头插法重组链表 while(new1 != null){ ListNode te=new1.next; new1.next=x.next; x.next=new1; x=new1.next; new1=te; } } public ListNode reverse(ListNode head) { ListNode temp = null; ListNode cur = head; ListNode pre = null; while(cur != null){ temp = cur.next; cur.next = pre; pre = cur; cur = temp; } return pre; } }欢迎分享,转载请注明来源:内存溢出
赞
(0)
打赏
微信扫一扫
支付宝扫一扫
![微信扫一扫](/view/img/theme/weipay.png)
![支付宝扫一扫](/view/img/theme/alipay.png)
(接上一篇)嵌入式c语言中关于几种控制流语句的分析和详细说明。
上一篇
2022-12-17
MIS课设 JavaFX考试管理系统
下一篇
2022-12-17
评论列表(0条)