2016-04-08 62 views
0

所以我試圖用Java構造一個方法,當被調用的時候,參數LinkedList的末尾有多少元素會被顛倒。如何從第n個元素開始反向鏈接列表

所以,如果我有

{hat cat bat mat} 

和我輸入2作爲我的參數,那麼最後2個元素將被扭轉這樣

{hat cat mat bat} 

這是我曾嘗試:

public void reverseLastFew(int howMany) 
    { 
     int s = size(); 
     LinkedListIterator iter1 = new LinkedListIterator(); 
     LinkedListIterator iter2 = new LinkedListIterator(); 
     for (int i=0;i<s-howMany;i++) 
     { 
      iter1.next(); 
     } 
     for (int i = 0;i<s;i++) 
     { 
      iter2.next(); 
     } 
     Object temp = null; 
     while (iter2.hasNext()) 
     { 
      temp = iter2.next(); 
     } 
     iter2.remove(); 
     iter1.add(temp); 

    } 
+0

你需要一個java代碼或解釋? –

回答

0

你可以試試這個代碼..........

import java.util.LinkedList; 

public class LinkListTry { 
public LinkedList<String> linkedlist; 

public LinkListTry(){ 
    linkedlist = new LinkedList<String>(); 
} 

public void insertElement(String element){ 
    linkedlist.add(element); 
} 

public void printListElement(){ 
    System.out.println(linkedlist); 
} 

public void reverseLastFewElement(int howmany){ 
    LinkedList<String> temp = new LinkedList<String>(); 
    while(howmany > 0){ 
     String str = linkedlist.removeLast(); 
     temp.add(str); 
     --howmany; 
    } 
    linkedlist.addAll(temp); 
} 
} 



public class LinkedListTryMain { 
public static void main(String[] args){ 
    LinkListTry test = new LinkListTry(); 
    test.insertElement("hat"); 
    test.insertElement("cat"); 
    test.insertElement("bat"); 
    test.insertElement("mat"); 

    test.printListElement(); 
    test.reverseLastFewElement(2); 
    test.printListElement(); 
} 
} 
1

我有一個解決類似的問題:

Reverse a linked list from position m to n. Do it in-place and in one-pass. 

For example: 
Given "1"->"2"->"3"->"4"->"5"->NULL, m = 2 and n = 4, 

return "1"->"4"->"3"->"2"->"5"->NULL. 

解決方案:

/** 
* Definition for singly-linked list. 
* public class ListNode { 
*  String val; 
*  ListNode next; 
*  ListNode(String x) { 
*   val = x; 
*   next = null; 
*  } 
* } 
*/ 
public class Solution { 
    public ListNode reverseBetween(ListNode head, int m, int n) { 
     if (head==null) { 
      return null; 
     } 

     ListNode dummy = new ListNode(" "); 
     dummy.next = head; 
     head = dummy; 

     for (int i=1; i<m; i++) { 
      head = head.next; 
     } 

     ListNode pre = head; 
     ListNode start = head.next; 
     ListNode end = start; 
     ListNode post = start.next; 

     for (int i=m; i<n; i++) { 
      if (post==null) { 
       return null; 
      } 

      ListNode temp = post.next; 
      post.next = end; 
      end = post; 
      post = temp; 
     } 

     start.next = post; 
     pre.next = end; 

     return dummy.next; 
    } 
} 

所以,你可以計算mn與你有什麼,或修改該解決方案爲您解決直接提問。無論如何,這個就地和單程解決方案非常好。

相關問題