/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void run(ListNode*head, int &num)//遍历链表,得到链表的长度; { while (head != NULL) { num++; head = head->next; } } ListNode* removeNthFromEnd(ListNode* head, int n) { int num=0; if (head == NULL) return NULL; run(head, num); if (n > num) cout << "删除位置不合法"; else { ListNode*p = NULL,*q=NULL; int i = 1; if (n == num)//删除首结点; { q = head; head = head->next; delete q; } else//删除的不是首结点 { q = head->next; p = head; while (i < num-n) { p = q; q = q->next; i++; } p->next = q->next; delete q; } return head; } } };
Remove Nth Node From End of List
原创shineprince ©著作权
©著作权归作者所有:来自51CTO博客作者shineprince的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:3Sum
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
java map循环中remove
java map循环中remove
迭代 Java 迭代器 -
19. Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and retur
leetcode-java i++ 两个指针 java