19. Remove Nth Node From End of List
来源:互联网 发布:淘宝判定为广告的评价 编辑:程序博客网 时间:2024/05/28 05:16
考察点:链表,指针;
思路:过滤掉特殊情况,然后是通用情况;
C++ 代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { if (!head) return head; if (head->next == NULL && n == 1) return NULL; int len = 0; ListNode * temp_len = head; while (temp_len){ len++; temp_len = temp_len->next; } if (n >=len) { temp_len = head->next; free(head); return temp_len; }// 长度等于n的情况 int i=0; ListNode * after = head; ListNode * before = head; while (after->next) { i++; if (i == n) { before = head; } if (i > n) { before = before->next; } after = after->next; } ListNode * temp = before->next; before->next = temp->next; free(temp); return head; }};
discuss中的奇淫技巧:
代码:
class Solution{public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode** t1 = &head, *t2 = head; for(int i = 1; i < n; ++i) { t2 = t2->next; } while(t2->next != NULL) { t1 = &((*t1)->next); t2 = t2->next; } *t1 = (*t1)->next; return head; }};
阅读全文
0 0
- 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
- Remove Nth Node From End of List
- Div+CSS 布局大全
- 210. Course Schedule II
- 617. Merge Two Binary Trees
- 310. Minimum Height Trees
- 513. Find Bottom Left Tree Value 树 BFS
- 19. Remove Nth Node From End of List
- 浅析JVM类加载机制
- 515. Find Largest Value in Each Tree Row 找到数每一层的最大值
- C++动态分配内存空间 : new 和 delete
- 576. Out of Boundary Paths
- 638. Shopping Offers 深度优先遍历、递归、存储技术(基于递归的动态规划)
- oracle触发器分类
- redis的自启设置
- DFS(深度搜索)——基于回溯法和递归