题解 | #调整牛群顺序#

调整牛群顺序

https://www.nowcoder.com/practice/a1f432134c31416b8b2957e66961b7d4

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode moveNthToEnd (ListNode head, int n) {
        // write code here
        if(head.next == null){
            return head;
        }
        ListNode reverseNode = reverse(head);
        ListNode tempNode = null;
        int i = 0;
        int res = 0;
        while(reverseNode!=null){
            i++;
            if(i == n){
                // 到达想要节点取值跳过该节点
                res = reverseNode.val;
                reverseNode = reverseNode.next;
            }else{
                // 再次反转
                ListNode tmp = reverseNode.next;
                reverseNode.next = tempNode;
                tempNode = reverseNode;
                reverseNode = tmp;
            }
        }

        // 将获取的节点先头插后反转
       ListNode result = new ListNode(res);
       result.next = reverse(tempNode);
        return reverse(result);
    }

    // 反转链表
    public ListNode reverse(ListNode head){
        ListNode result = null;
        ListNode cur = head;
        while(cur != null){
            ListNode tmp = cur.next;
            cur.next = result;
            result = cur;
            cur = tmp;
        }
        return result;
    }
}

全部评论

相关推荐

11-04 19:05
已编辑
东莞城市学院 单片机
不知道怎么取名字_:你这个要实习两年?哪有这么久的,感觉就是即使你毕业了,但还按实习的话,是不是不用给你缴社保公积金啥的
点赞 评论 收藏
分享
飞屋一号:包住还有每工作日餐补,已经比很多公司的实习强了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务