19. Remove Nth Node From End of List(链表)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyuanzong/article/details/80232573

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

题目:删除倒数第n个节点(遍历只能一趟)

思路:双指针

例如:1->2->3->4->5,  n = 2
代码原理如下

t1的值     t1->next的值          t的值     n的值
0          1                    1         2
0          1                    2         1
0          1                    3         0
1          2                    4         0
2          3                    5         0
3          4                    NULL      0

需要删除的是:4

t1->next = t1->next->next 即可删除4

代码如下

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
              ListNode *t1 = new ListNode(0);
              ListNode *t = head;
              t1->next = head;
              head = t1;

              while(n || t) {

                    t = t->next;
                    t1 = (n?t1:t1->next);
                    n = (n?n-1:n);
              }

              t1->next = t1->next->next; //删除倒数第n个节点

              return head->next;

    }
};

猜你喜欢

转载自blog.csdn.net/tangyuanzong/article/details/80232573