《程序员代码面试指南》第二章 链表问题 反转部分单向链表
生活随笔
收集整理的這篇文章主要介紹了
《程序员代码面试指南》第二章 链表问题 反转部分单向链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
給一個單向鏈表和開始和結束的位置,將這兩位置區間鏈表進行反轉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
總結
以上是生活随笔為你收集整理的《程序员代码面试指南》第二章 链表问题 反转部分单向链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android:四大架构的优缺点,你真的
- 下一篇: react+mobx:如何组织store