• 【leetcode】19. Remove Nth Node From End of List


    题目描述:

    Given a linked list, remove the nth node from the end of list and return its head.

    解题分析:

    这个题的关键是找到倒数第n个节点:设置两个标记变量,想让其中1个走n-1步,然后两个一起往后走,当第一个变量指向表尾时,第二个变量就指向要删除的节点。

    具体代码:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10    
    11     public static ListNode removeNthFromEnd(ListNode head, int n) {
    12         if(n==0){
    13             ListNode node =head;
    14             node.next=null;
    15             head=head.next;
    16             return head;
    17         }
    18         int count=0;
    19         ListNode node = head;
    20         //让node变量先走n步
    21         while(count<n){
    22             node=node.next;
    23             count++;
    24         }
    25         //current表示要被删除的节点,pre表示current的上一个节点
    26         ListNode pre=null;
    27         ListNode current=head;
    28         while(node!=null){
    29             node=node.next;
    30             pre=current;
    31             current=current.next;
    32         }
    33         if(pre!=null){
    34             pre.next=current.next;
    35         }
    36         //被删除的节点是头结点的情况要单独判断
    37         else{
    38             pre=head;
    39             current=head.next;
    40             pre.next=null;
    41             head=current;
    42         }
    43         return head;
    44     }
    45 }
  • 相关阅读:
    最简单的jQuery插件
    SQL执行时间
    Resharper 8.2 注册码
    Module模式
    RestSharp使用
    使用MVC过滤器保存操作日志
    Ajax Post 类实例
    IBatis分页显示
    IBatis插入类的实例
    Topcoder SRM629 DIV2 解题报告
  • 原文地址:https://www.cnblogs.com/godlei/p/5642151.html
Copyright © 2020-2023  润新知