【Leetcode】19. Remove Nth Node From End of List

本文介绍两种高效算法来解决链表中倒数第N个节点的删除问题。第一种方法通过两次遍历获取链表长度,再定位到目标节点;第二种方法采用双指针技巧,一次遍历即可完成删除操作。

方法一:

思路:

(1)若链表为空,直接返回null。

(2)求链表的长度len。

(3)若n==len,则删除的是第一个节点,直接删除后返回即可。

(4)从头开始遍历链表,找到待删除节点cur,并用pre记录其前驱结点。

(5)若pre不为空,说明删除的不是第一个节点,直接置pre.next=cur.next即可。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
	public ListNode removeNthFromEnd(ListNode head, int n) {
		if (head == null)
			return null;
		ListNode cur = head, pre = null;
		int len = 0;
		while (cur != null) {
			cur = cur.next;
			len++;
		}
		if (n == len) {
			head = head.next;
			return head;
		}
		cur = head;
		for (int i = 0; i < len - n; i++) {
			pre = cur;
			cur = cur.next;
		}
		if (pre != null)	   
			pre.next = cur.next;
		return head;
	}
}

Runtime:15ms


方法二:双指针

思路:

(1)双指针:设置两个指针first跟second。

(2)first指针先移动n步。

(3)若first指针为空,则表示要删除的是头节点,此时直接返回head->next即可。

(4)first指针不为空,则将两个指针一起移动,直到first指针指向最后一个节点,令second->next=second->next->next即可。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
	public ListNode removeNthFromEnd(ListNode head, int n) {
		if (head == null)
			return head;
		ListNode first = head, second = head;
		for (int i = 0; i < n; i++)
			first = first.next;
		if (first != null) {
			while (first.next != null) {
				first = first.next;
				second = second.next;
			}
			second.next = second.next.next;
		}
		else
			head = head.next;
		return head;
	}
}

Runtime:15ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值