1. 程式人生 > >Leetcode之Remove Nth Node From End of List

Leetcode之Remove Nth Node From End of List

題目:

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.

Note:

Given n will always be valid.

程式碼:

#include<iostream>
using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x):val(x),next(NULL){}
};

ListNode* removeNthFromEnd(ListNode* head, int n) {
	int count = 1;
	ListNode* p = head;
	while (p->next != NULL) {
		count++;
		p = p->next;
	}
	int mn = count - n;

	if (mn == 0)return head->next;
	ListNode* o = head;
	ListNode* k = o->next;
	for (int i = 1; i < mn; i++) {
		o = k;
		k = o->next;
	}

	if (k == NULL)return NULL;
	o->next = k->next;

	return head;
}

int main() {
	
	ListNode n1(1);
	ListNode n2(2);
	ListNode n3(3);
	ListNode n4(4);
	ListNode n5(5);
	n1.next = &n2;
	n2.next = &n3;
	n3.next = &n4;
	n4.next = &n5;

	ListNode* p = removeNthFromEnd(&n1, 1);

	while (p != NULL) {
		cout << p->val << " ";
		p = p->next;
	}
	
	
	return 0;
}

注意事項:

1、考慮元素全部刪完的情況

2、考慮刪除的是頭元素的情況