首页 > 其他 > 详细

LeetCode 19. Remove Nth Node From End of List

时间:2021-03-08 22:12:10      阅读:42      评论:0      收藏:0      [点我收藏+]

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

Follow up: Could you do this in one pass?

Example 1:

技术分享图片

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

实现思路:

要剔除倒数第K个链表结点,于是可以进行统计链表总结点个数N,然后删除第N-K个结点即可。

AC代码:

class Solution {
	public:
		ListNode* removeNthFromEnd(ListNode* head, int n) {
			ListNode* temp=head;
			int allNum=0;//统计所有结点的个数
			while(temp!=NULL) {
				allNum++;
				temp=temp->next;
			}
			if(n>allNum) {
				return head;
			} else if(n==allNum) {
				head=head->next;
				return head;
			} else {
				int bgPos=allNum-n,cnt=0;//开始删除结点的位置
				temp=head;
				while(temp!=NULL) {
					cnt++;
					if(cnt==bgPos) {
						if(temp->next!=NULL) {
							temp->next=temp->next->next;
						} else temp->next=NULL;
						break;
					}
					temp=temp->next;
				}
			}
			return head;
		}
};

LeetCode 19. Remove Nth Node From End of List

原文:https://www.cnblogs.com/coderJ-one/p/14502050.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!