【Leetcode】Remove Nth Node From End of List

题目链接:https://leetcode.com/problems/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.

思路:

1、先求链表长度,遍历链表找到要删除结点需要的指针,需要遍历两遍。

2、用两个指针,两指针距离为n,并且每次移动一步,直到表尾,此时前一个指针指向的就是倒数第n个结点

算法1:

public int getListLength(ListNode head) {
		int length = 0;
		ListNode p = head;
		while (p != null) {
			length++;
			p = p.next;
		}
		return length;
	}

	public ListNode removeNthFromEnd(ListNode head, int n) {
		int length = getListLength(head);
		ListNode pre = null, p = head;
		int i = length - n + 1;// 正序移动距离
		while (--i > 0) {// 获取要删除节点的指针
			pre = p;
			p = p.next;
		}
		if (pre != null) {
			pre.next = p.next;
		} else {
			head = p.next;// 当删除头节点时
		}
		return head;
	}


算法2:

	public ListNode removeNthFromEnd(ListNode head, int n) {
		// nth指向p前n个结点,pre为nth前一个结点,即pre/nth/p
		ListNode p = head, nth = head, pre = null;
		while (--n > 0) {
			p = p.next;
		}
		while (p.next != null) {
			p = p.next;
			pre = nth;
			nth = nth.next;
		}
		// 此时p指向表尾,nth指向倒数n个结点
		if(pre==null){ //如果删除的是头结点
			head = nth.next;
		}else{
			pre.next = nth.next;
		}
		return head;
	}


算法3:

考虑上面的算法需要考虑到如果删除的是表头,需要单独处理,经常在别人的题解中见到头结点可以将表头当普通结点一样操作,简化程序。

下面的代码就是加了头结点。

	public ListNode removeNthFromEnd(ListNode head, int n) {
		// nth指向p前n个结点,pre为nth前一个结点,即pre/nth/p
		ListNode newHead = new ListNode(0);// 头结点
		ListNode p = head, nth = head, pre = newHead;
		newHead.next = head;
		while (--n > 0) {
			p = p.next;
		}
		while (p.next != null) {
			p = p.next;
			pre = nth;
			nth = nth.next;
		}
		// 此时p指向表尾,nth指向倒数n个结点
		pre.next = nth.next;
		return newHead.next;
	}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值