zoukankan      html  css  js  c++  java
  • leetcode:Remove Nth Node From End of List (移除从尾部数的第N个节点)

    Question:

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

    For example,

       Given linked list: 1->2->3->4->5, and n = 2.
    
       After removing the second node from the end, the linked list becomes 1->2->3->5.
    

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */

    Note:
    Given n will always be valid.
    Try to do this in one pass.

     

    给定一个链表,如上边数据结构所示,删除倒数第N个节点。

    算法思想:① 没有想起十分高效的方法,但是时间复杂度仍然是O(n),就是先要遍历整个链表,看有几个节点,比如有n1个。

                  ②  假如要删除倒数n个节点,然后对链表遍历到第n1-n的位置,执行删除操作,要特别注意的是如果要删除的元素是链表的第一个元素该单独处理。

    代码设计:

     1 class Solution{
     2     public ListNode removeNthFromEnd(ListNode head, int n) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         int temp=count(head)-n;
     5         if(0==temp)
     6             return head.next; //如果要删除第一个节点
     7         ListNode h=new ListNode(-1); //临时节点用来当首地址,记录head指向的位置
     8         h.next=head;
     9         ListNode p=h;
    10         for(int i=0;i<temp;i++)//找到要删除节点的前一个位置
    11             p=p.next;
    12         ListNode del=p.next; //删除节点
    13         p.next=del.next;
    14         del=null;  //释放要删除节点的内存空间
    15         p=h.next;  
    16         h=null;        //释放临时节点的内存空间
    17         return p;
    18     }
    19     public int count(ListNode l1){  //计算链表节点数
    20         int i=0;
    21         while(l1!=null){
    22             i++;
    23             l1=l1.next;
    24         }
    25         //System.out.println(i);
    26         return i;
    27     }
    28 }

    2013-10-24 01:57:13

  • 相关阅读:
    12.C语言控制窗口
    11.字符,字符常见开发,_itoa函数
    Clusterware 和 RAC 中的域名解析的配置校验和检查 (文档 ID 1945838.1)
    导致实例逐出的五大问题 (文档 ID 1526186.1)
    如何诊断 11.2 集群节点驱逐问题 (文档 ID 1674872.1)
    11gR2新特性---Gpnp守护进程
    CSS 功能简介
    11gR2新特性---gipc守护进程
    10g集群启动顺序
    11gR2集群件任务角色分离(Job Role Separation)简介
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/DeleteNode.html
Copyright © 2011-2022 走看看