关闭

leetcode 019 —— Remove Nth Node From End of List

77人阅读 评论(0) 收藏 举报
分类:

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;
	}
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:25569次
    • 积分:2052
    • 等级:
    • 排名:第18651名
    • 原创:188篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    最新评论