LeetCode OJ 19. Remove Nth Node From End of List

时间:2023-03-09 22:17:06
LeetCode OJ 19. Remove Nth Node From End of List

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.

Subscribe to see which companies asked this question

解答:

额这道题没想出什么好方法……感觉这样要两次遍历好烦啊……当然链表嘛就要注意头节点……有空再看看吧TAT

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode *tmp = head;
    ;

    while(NULL != tmp){
        count++;
        tmp = tmp->next;
    }
    if(count == n){
        return head->next;
    }
    tmp = head;
    ){
        count--;
        tmp = tmp->next;
    }
    tmp->next = tmp->next->next;
    return head;
}