如何从第n个元素到结尾反转此链接列表

时间:2016-04-08 00:28:05

标签: java algorithm

所以我试图在Java中构建一个方法,当被调用时,将LinkedList末尾的元素将被反转为参数。

所以,如果我有

{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);

   }

2 个答案:

答案 0 :(得分: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,或修改此解决方案以直接解决您的问题。无论如何,这种就地和一次通过的解决方案非常好。

答案 1 :(得分: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();
}
}