Remove Nth Node From End of List

由于一般的链表不包含表头,所以使得处理第一个节点相较于其他节点具有特殊性,所以我的思路是先转化为含表头的的链表,再进行操作,最后还原成没有表头的链表,并返回。
#include<iostream>
using namespace std;

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

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
		struct ListNode n0(0);
		n0.next = head;
		struct ListNode *p1, *p2;
		p1 = &n0;
		p2 = &n0;
		for(int i = 1; i <= n; i++) {
			p1 = p1 -> next;
		}
		for(; p1 -> next != NULL; ) {
			p1 = p1 -> next;
			p2 = p2 -> next;
		}
		p2 -> next = p2 -> next -> next;
		struct ListNode *headNew;
		headNew = n0.next;
		
	
		//getchar();
		return headNew;
        
    }
};


int main() {
	struct ListNode n1(1),n2(2),n3(3),n4(4),n5(5);
	n1.next = &n2; n2.next = &n3; n3.next = &n4; n4.next = &n5; n5.next = NULL;
	struct ListNode *head = &n1;
	int n = 5;

	Solution solution;
	struct ListNode *tmp = solution.removeNthFromEnd(head, n);
	for(; tmp != NULL; ) {
		cout << tmp ->val << endl;
		tmp = tmp ->next;
	}
	getchar();
	return 1;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值