#include<iostream> usingnamespacestd; //Definition for singly-linked list. structListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };
classSolution { public: ListNode* removeNthFromEnd(ListNode* head, int n){ int length1=1; ListNode* p = head; ListNode* q = head; while (p->next) { length1++; p = p->next;
} int cha = length1 - n; //if (length1 == 1) // return NULL;
if (length1 <= n) head = head->next; else { for (int i = 0; i < (cha - 1); i++) { q = q->next; } ListNode *t = q->next; q->next = t->next; delete t; } return head; } };
测试结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
intmain(){
/*Solution *s;*/ ListNode* l1 = new ListNode(1); ListNode *l11 = l1; l11->next = new ListNode(2); l11 = l11->next; l11->next = new ListNode(3); l11 = l11->next; l11->next = new ListNode(4); l11 = l11->next; l11->next = new ListNode(5); Solution* s = new Solution; s->removeNthFromEnd(l1, 1); system("pause"); return0; }