LeetCode 19 Remove Nth Node From End of List

本文详细介绍了如何使用链表操作解决删除链表倒数第n个节点的问题,包括基本思路和两种简化做法。文章还提供了代码实现,帮助读者理解并实践这一算法。

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.

解题思路:这道题比较容易,是一道链表操作题,首先进行遍历,记录下长度,然后再遍历,这时就可以删除指定的节点,此时的时间复杂度为O(N+M),这是最简单的一种做法,但是要考虑删除为头结点和尾节点这两种特殊情况。

代码如下:

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
 public ListNode removeNthFromEnd(ListNode head, int n) {
    //删除链表倒数第n个结点 从1开始计数
    	ListNode temp = head;
    	int size =0;
    	while(temp.next!=null){
    		temp = temp.next;
    		size++;
    	}
    	if(size==0){//size从0开始计算
    		return null;
    	}
    	ListNode temp1 = head;
    	int t = size - n;
    	int index=0;
    	//若删除结点为第一个则如此操作
    	if(t==-1){
    		head = head.next;
    		return head;
    	}
    	while(temp1.next!=null){
    		if(index==t){
    			if(t==size-1){//若删除最后一个结点则如此操作
    				temp1.next=null;
    				break;
    			}
    		  temp1.next = temp1.next.next;
    		}
    		temp1 = temp1.next;
    		index++;
    	}
    	return head;    
    }
}

当然,Accept之后从Discuss中发现,也有更加简易的做法,在这里学习两个:

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    static int depth = 0, levels = 0;

    if (!head) {levels = depth++; return NULL;}
    depth++;
    head->next = removeNthFromEnd (head->next, n);
    depth--;
    if (levels - depth + 1 == n) return head->next;
    return head;
}

public ListNode RemoveNthFromEnd(ListNode head, int n) {
    ListNode h1=head, h2=head;
    while(n-->0) h2=h2.next;
    if(h2==null)return head.next;  // The head need to be removed, do it.
    h2=h2.next;

    while(h2!=null){
        h1=h1.next;
        h2=h2.next;
    }
    h1.next=h1.next.next;   // the one after the h1 need to be removed
    return head;
}

人家都是one pass,leetcode真是高手如林。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值