9_leetcode_remove Nth Node from End
来源:互联网 发布:方媛moka的淘宝店 编辑:程序博客网 时间:2024/05/24 04:49
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.
Note:
Given n will always be valid.
Try to do this in one pass.
//1.链表为空或n不大于0 ; 2.设置两个指针,fast和slow。fast先走n步。3.删除节点考虑三种情况,当倒数第n个节点是头节点, 或者为尾节点,或者时中间节点。三种情况 4.最后一种情况,n大约链表中节点的个数
ListNode *removeNthFromEnd(ListNode *head, int n) { if(head == NULL || n <= 0) return head; ListNode* slow = head; ListNode* fast = head; int i = 0; while(i < n) { fast = fast->next; i++; if(fast == NULL) break; } if(i == n) { if(fast == NULL) { ListNode* resultHead = head->next; delete head; return resultHead; } else { while(fast->next) { slow = slow->next; fast = fast->next; } ListNode* deleteNode = slow->next; slow->next = deleteNode->next; delete deleteNode; return head; } } else { return head; } }
0 0
- 9_leetcode_remove Nth Node from End
- leetCode(9):Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- TOJ 4074 Running Laps -- 树状数组
- Usid与Guid的一些理解
- Windows 7 X64 中 PL/SQL Developer 连接 Oracle 11g Database
- 排序算法收集整理
- 每日算法之二十九:Search in Rotated Sorted Array
- 9_leetcode_remove Nth Node from End
- 计算机视觉与模式识别 code
- UVa 10487 - Closest Sums
- c/c++指针2
- 线程池
- UILable使用
- void glutPositionWindow(int x, int y); 窗口API(2)
- 阿里云服务器实战(一) : 在Linux下Tomcat7下使用连接池
- LeetCode Binary Tree Maximum Path Sum