日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

《程序员代码面试指南》第二章 链表问题 反转部分单向链表

發布時間:2025/3/15 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 《程序员代码面试指南》第二章 链表问题 反转部分单向链表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

給一個單向鏈表和開始和結束的位置,將這兩位置區間鏈表進行反轉

java代碼

/*** @Description:反轉部分單向鏈表* @Author: lizhouwei* @CreateDate: 2018/4/6 20:30* @Modify by:* @ModifyDate: */ public class Chapter2_7 {public Node reversePart(Node head, int startIndex, int endIndex) {if (head == null || startIndex <= 0 || startIndex > endIndex) {return head;}Node preNode = null;//開始鏈表的前驅節點Node postNode = null;//結束節點的后繼節點int len = 0;//鏈表長度Node cur = head;while (cur != null) {len++;preNode = len == startIndex - 1 ? cur : preNode;postNode = len == endIndex + 1 ? cur : postNode;cur = cur.next;}if(startIndex>len){return head;}Node node1 = preNode==null?head:preNode.next;Node node2 =node1.next;node1.next = postNode;Node next=null;while (node2!=postNode){next = node2.next;node2.next =node1;node1 =node2;node2 = next;}//若preNode !=null,則不是從head開始反轉的,鏈表頭部依然是headif (preNode!=null){postNode.next = node1;return head;}//若preNode =null,則是從head開始反轉的return node1;}//測試public static void main(String[] args) {Chapter2_7 chapter = new Chapter2_7();Link link = new Link();//構造兩個鏈表for (int i = 10; i > 0; i--) {link.add(i);}Link.printLink(link.head);Node head = chapter.reversePart(link.head,1,5);Link.printLink(head);} }

轉載于:https://www.cnblogs.com/lizhouwei/p/8728920.html

總結

以上是生活随笔為你收集整理的《程序员代码面试指南》第二章 链表问题 反转部分单向链表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。