java - 如何反转这个从第 n 个元素到最后的链表

标签 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);

   }

最佳答案

我有一个类似问题的解决方案:

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,或者修改此解决方案以直接解决您的问题。无论如何,这种就地一次性解决方案非常好。

关于java - 如何反转这个从第 n 个元素到最后的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36489501/

相关文章:

java - 为什么在Java中的文件输入输出代码中出现一些错误?

java - Java Process 没有输出到标准输出

java - 如何访问Action或dispatch action类中action标签(struts-config.xml)的path属性?

java - 在 Java 中 : is where a way to create a subarray that will point to a portion of a bigger array?

algorithm - 约翰卡马克不寻常的快速平方根反函数(Quake III)

javascript - BODMAS 计算器

java - 在 Java 中查找所有可能的 'StringPairGroups' 的算法?

algorithm - 如何将多边形转换为非重叠三角形的集合?

javascript - 将对象数组转换为数组中对象属性的对象

java - jtree右键只选择一个节点