Lc19_删除链表的倒数第N个节点


//给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 
//
// 示例: 
//
// 给定一个链表: 1->2->3->4->5, 和 n = 2.
//
//当删除了倒数第二个节点后,链表变为 1->2->3->5.
// 
//
// 说明: 
//
// 给定的 n 保证是有效的。 
//
// 进阶: 
//
// 你能尝试使用一趟扫描实现吗? 
// Related Topics 链表 双指针

package leetcode.editor.cn;

import com.example.demo.ArrayConvertLinkedList;
import com.example.demo.ListNode;

//Java:删除链表的倒数第N个节点
public class P19RemoveNthNodeFromEndOfList {
    public static void main(String[] args) {
        Solution solution = new P19RemoveNthNodeFromEndOfList().new Solution();
        // TO TEST
        int[] array1 = {1,2,3,4,5};
        int n =2;
        ListNode head1 = ArrayConvertLinkedList.arrayToNode(array1);
        ListNode res = solution.removeNthFromEnd(head1,n);
        ArrayConvertLinkedList.printNode(res);
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head == null) {
                return head;
            }
            int len = 0;
            ListNode curr = head;
            while (curr != null) {
                len++;
                curr = curr.next;
            }
            int delPosition = len - n - 1;
            if (delPosition==-1) {
                head = head.next;
                return head;
            }
            int currPosition = 0;
            ListNode curr2 = head;
            while (head != null) {
                if (currPosition != delPosition) {
                    currPosition++;
                    curr2 = curr2.next;
                } else {
                    curr2.next = curr2.next.next;
                    return head;
                }
            }
            return null;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
posted @ 2020-07-09 09:22  小傻孩丶儿  阅读(104)  评论(0编辑  收藏  举报