删除链表的倒数第N个节点

给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

你能尝试使用一趟扫描实现吗?

给定的 n 保证是有效的。

 

/**
 * 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 *p = head;
        ListNode *q = head;
        for(int i = 0; i < n; i++){
            if(q->next != NULL){
                q = q->next;
            }
                
            else{
                head = head->next;
                return head;
            }
        }
        while(q->next != NULL){
            q = q->next;
            p = p->next;
        }
        p->next = p->next->next;
        return head;
    }
};

 

posted @ 2020-03-11 19:43  jenningszheng  阅读(188)  评论(0编辑  收藏  举报