【Leetcode】【Easy】Remove Nth Node From End of List
2014-12-05 05:29
441 查看
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
普通青年解法:
设置三个指针A\B\C,指针A和B间隔n-1个结点,B在前A在后,用指针A去遍历链表直到指向最后一个元素,则此时指针B指向的结点为要删除的结点,指针C指向指针B的pre,方便删除的操作。
代码:
文艺智慧青年解法:
(需要更多理解)
附录:
C++二重指针深入
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.
普通青年解法:
设置三个指针A\B\C,指针A和B间隔n-1个结点,B在前A在后,用指针A去遍历链表直到指向最后一个元素,则此时指针B指向的结点为要删除的结点,指针C指向指针B的pre,方便删除的操作。
代码:
/** * 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) { ListNode *target = head; ListNode *target_pre = NULL; ListNode *findthelast = head; if (head == NULL) return head; while(--n>0) findthelast = findthelast->next; while (findthelast->next) { target_pre = target; target = target->next; findthelast = findthelast->next; } if (target_pre == NULL) { head = target->next; return head; } target_pre->next = target->next; return head; } };
文艺智慧青年解法:
(需要更多理解)
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; } };
附录:
C++二重指针深入
相关文章推荐
- Leetcode[Easy] - Remove Nth Node From End of List
- [Leetcode 19, Easy] 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 (easy)
- Leetcode 19. Remove Nth Node From End of List (Easy) (cpp)
- 【leetcode】Remove Nth Node From End of List(easy)
- [leetcode] 19. Remove Nth Node From End of List python实现【easy】
- 【Leetcode-easy】Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- leetcode -- Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List 解题报告
- LeetCode - Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List