zoukankan      html  css  js  c++  java
  • LeetCode 19.删除链表的倒数第 n 个节点

    给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

    示例:

    给定一个链表: 1->2->3->4->5, 和 n = 2.
    
    当删除了倒数第二个节点后,链表变为 1->2->3->5.
    

    说明:

    给定的 n 保证是有效的。

    进阶:

    你能尝试使用一趟扫描实现吗?

    双指针法:

    /**
     * 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) {
            ListNode fast = head;
            ListNode slow = head;
            for(int j = 0; j < n; j++) {
                fast = fast.next;
            }
            if(fast == null) { //如果删除的是第一个节点
                return head.next;
            }
            while(fast.next != null) {
                fast = fast.next;
                slow = slow.next;
            }
            slow.next = slow.next.next; //删除slow.next
            return head;
        }
    }
    
    如果博客内容有误,请联系我修改指正,非常感谢! 如果觉得这篇博客对你有用的话,就帮我点个小小的赞吧! 一起加油鸭, 越努力,越幸运!!!
  • 相关阅读:
    ZOJ 2158 Truck History
    Knight Moves (zoj 1091 poj2243)BFS
    poj 1270 Following Orders
    poj 2935 Basic Wall Maze (BFS)
    Holedox Moving (zoj 1361 poj 1324)bfs
    ZOJ 1083 Frame Stacking
    zoj 2193 Window Pains
    hdu1412{A} + {B}
    hdu2031进制转换
    openjudge最长单词
  • 原文地址:https://www.cnblogs.com/studywithme/p/13552588.html
Copyright © 2011-2022 走看看