【leetcode】【单链表】【19】Remove Nth Node From End of List
2015-05-13 16:42
489 查看
#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) { int numOfNode = 0; ListNode* cur = head; while (cur){ //统计节点个数 ++numOfNode; cur = cur->next; } int beforeDelete = numOfNode - n; ListNode* temp = NULL; if (beforeDelete == 0){ //删除头结点情况 temp = head; head = head->next; }else{ //删除非头结点情况 cur = head; while (--beforeDelete > 0) cur = cur->next; temp = cur->next; cur->next = temp->next; } delete temp; return head; } ListNode* createList(ListNode* head){ int numOfNode; int value; cout << "please input number of listNode:"; cin >> numOfNode; cin >> value; head = new ListNode(value); ListNode* cur = head; for (int i = 1; i < numOfNode; ++i){ cin >> value; ListNode* temp = new ListNode(value); cur->next = temp; cur = temp; } return head; } void printNode(ListNode* head){ ListNode* cur = head; while (cur){ cout << cur->val << " "; cur = cur->next; } cout << endl; } }; int main(){ ListNode* head = NULL; Solution lst; head = lst.createList(head); lst.printNode(head); head = lst.removeNthFromEnd(head, 2); lst.printNode(head); system("pause"); return 0; }
相关文章推荐
- 1.1数组和链表:19. Remove Nth Node From End of List(Leetcode)
- leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
- LeetCode 19. Remove Nth Node From End of List(删除链表)
- leetcode 19. Remove Nth Node From End of List-移除链表元素|双指针
- leetcode[#19 链表 标尺]Remove Nth Node From End of List
- 【Leetcode】19. Remove Nth Node From End of List - 删掉链表倒数第n个节点
- Leetcode 19 Remove Nth Node From End of List 链表
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- leetcode 19. Remove Nth Node From End of List 单向链表删除第n个数
- 【leetcode】【单链表】【19】Remove Nth Node From End of List
- [LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点
- [leetcode] 【链表】19. Remove Nth Node From End of List
- LeetCode-19-Remove-Nth-Node-From-End-of-List 链表水题
- LeetCode-19-Remove Nth Node From End of List(链表)-Easy
- leetcode_19题——Remove Nth Node From End of List(链表)
- leetCode 19. Remove Nth Node From End of List 链表
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- LeetCode 19. Remove Nth Node From End of List--删除链表的倒数第n个结点
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- leetcode 19. Remove Nth Node From End of List(链表)