题解 | #调整牛群顺序#

调整牛群顺序

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;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 12:10
点赞 评论 收藏
分享
点赞 评论 收藏
分享
Lorn的意义:你这标个前端是想找全栈吗?而且项目确实没什么含金量,技术栈太少了,边沉淀边找吧 现在学院本想就业好一点四年至少得高三模式两年加油吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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