zoukankan      html  css  js  c++  java
  • 【JAVA、C++】LeetCode 019 Remove Nth Node From End of List

    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.
    

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

    解题思路一:

    先计算length,然后删除

    JAVA实现:

    static public ListNode removeNthFromEnd(ListNode head, int n) {
    		if(n<=0)
    			return head;
    		ListNode ln=head;
    		int i=1;
    		while(ln.next!=null){
    			ln=ln.next;
    			i++;
    		}
    		if(i==n)
    			return head.next;
    		ln=head;
    		for(;i>n+1;i--)
    			ln=ln.next;
    		ln.next=ln.next.next;
    		return head;
    	}
    

     解题思路二:

    一个指针先走n步,另一个指针跟上。

    C++:

     1 class Solution {
     2 public:
     3     ListNode* removeNthFromEnd(ListNode* head, int n) {
     4         if (n <= 0)
     5             return head;
     6         ListNode* cur = head;
     7         for (int i = 0; i < n-1; i++) {
     8             if (cur->next != NULL)
     9                 cur = cur->next;
    10             else return head;
    11         }
    12         if (cur->next == NULL) {
    13             ListNode*temp = head;
    14             head = head->next;
    15             delete temp;
    16             return head;
    17         }
    18         cur = cur->next;
    19         ListNode* cur2 = head;
    20         while (cur->next != NULL) {
    21             cur2 = cur2->next;
    22             cur = cur->next;
    23         }
    24         cur = cur2->next;
    25         cur2->next = cur->next;
    26         delete cur;
    27         return head;
    28     }
    29 };
  • 相关阅读:
    PHPEXCEL 导出多个sheet
    android adb.exe端口占用
    imageview 显示assets的图片

    Java中日期问题
    java中的定时器的实现样例
    Oracle数据库如何干净的删除
    MySQL索引相关知识
    JavaScript基础知识总结
    JDBC技术总结
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4473394.html
Copyright © 2011-2022 走看看