【LeetCode】#19删除链表的倒数第N个节点(Remove Nth Node From End of List)

【LeetCode】#19删除链表的倒数第N个节点(Remove Nth Node From End of List)

题目描述

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例

给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.

Description

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

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.

解法

class Solution{
	public ListNode removeNthFromEnd(ListNode head, int n){
		if(head.next==null){
			head = null;
			return head;
		}
		int sum = 0;
		ListNode l = head;
		while(l!=null){
			sum++;
			l = l.next;
		}
		n = sum - n;
		l = head;
		if(n==0){
			return head.next;
		}
		for(int i=0; i<n-1; i++){
			l = l.next;
		}
		l.next = l.next.next;
		return head;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84721058
今日推荐