leetcode 019 —— 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.

思路:计算后移的次数即可

class Solution {
public:
	ListNode* removeNthFromEnd(ListNode* head, int n) {
		int move = heightOfList(head) - n;  //移动次数
		ListNode pre(0);
		ListNode *p=⪯
		p->next = head;
		ListNode* start = head;
		while (move){
			start = start->next;
			p = p->next;
			move--;
		}
		p->next = start->next;
		delete(start);
		return (&pre)->next;
	}
	int heightOfList(ListNode *head){
		int n = 0;
		//ListNode *a = head;
		while (head){
			head = head->next;
			n++;
		}
		return n;
	}
};


阅读更多
上一篇leetcode 018 —— 4Sum (nsum)
下一篇leetcode 020 —— Valid Parentheses
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭