leetcode算法练习【19】删除链表的倒数第N个节点

所有题目源代码:Git地址

题目

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

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 n 保证是有效的。

进阶:

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

方案:扫一遍,设置一个length巧妙的使得前后两个节点的保持一定的距离,直到最后一个节点,最后排除删除头部节点的特殊情况即可

/**
 * 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) {
        int length=0;
        ListNode temp_head = head;
        ListNode temp_tail = head;

        while(temp_tail.next!=null){
            temp_tail = temp_tail.next;
            if(length<n){
                length++;
            }else if(length >= n){
                temp_head = temp_head.next;
            }
        }
        if (length == n-1){
            //说明删除的是头部节点
            return temp_head.next;
        }else if(length >= n){
            //说明删除的是非头部节点
            temp_head.next = temp_head.next.next;
        }
        return head;
    }
}
复杂度计算
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
发布了135 篇原创文章 · 获赞 187 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/symuamua/article/details/105646091