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

    题目:

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

    示例:

    给定一个链表: 1->2->3->4->5, 和 n = 2.
    
    当删除了倒数第二个节点后,链表变为 1->2->3->5.
    /**
     * 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 dummy=new ListNode(0);
            dummy.next=head;
            ListNode first=head;
            
            int lenght=0;
            while(first!=null)
            {
                first=first.next;
                lenght++;
            }
            
            lenght=lenght-n;
            first=dummy;
            while(lenght>0)
            {
                lenght--;
                first=first.next;
            }
            first.next=first.next.next;
            
            return dummy.next;
        }
    }

    整体的思路:1)首先应该获取这个链表的长度,用一个指针指向头结点,然后遍历直到结点为空;

                          2)设置一个结点指向哑结点,因为倒数第n个节点,可以通过长度减去n就获得链表的第n个节点;

                          3)将获取到的指针下个节点指向下下的节点。

  • 相关阅读:
    mongoDb
    profile ,explain,
    header 里面的contenttype
    group by,distinct的使用(30万数据测试)
    ubuntu 12.04 mysql 错误 Errcode 13
    php curl,爬虫
    explain mysql
    php 文件的函数
    create User,grand,Load data file
    android 按钮点击测试
  • 原文地址:https://www.cnblogs.com/Optimism/p/10744133.html
Copyright © 2011-2022 走看看