Leetcode c语言-Remove Nth Node From End of List

来源:互联网 发布:宝石蓝颜色数据 编辑:程序博客网 时间:2024/06/06 01:53

Title:

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.


这道题目如果用一般的方法,非常容易,首先就是算出链表的长度,然后根据长度和n的关系进行处理,只需要当遇到要remove的节点事,将它的前一个节点 head->next=head->next->next,也就是跳过这个节点即可:


solution:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {    int i=0;    int len=0;    struct ListNode* temp_head =head;    struct ListNode* result_head =head;            while(temp_head != NULL) {        len++;            temp_head=temp_head->next;    }        if (len==1)        return NULL;       while(i<len-n-1){       result_head=result_head->next;       i++;   }   if ((len-n) == 0)       head=head->next;   else   result_head->next=result_head->next->next;       return head;    }


但是这种方法有两个遍历,题目要求说最好使用一个pass,那么就要想,肯定不能全部遍历完,再替换,因为这种操作是不存在的。因此要在遍历过程中,进行替换。那么如何确定要替换的节点的位置呢,这里就需要用到两个指针,第一个指针标明位置,比如第一个指针先向后移动n个,这个时候剩余的长度为len-n,这个长度正好是我们需要的,然后再用第二个指针,该指针和第一个指针同时向后移动,当第一个指针移到最后,那么第二个指针也就移到了len-n的位置,然后删掉该节点即可。

在这种操作中,要注意一点,当第一个指针移动n个后,该指针是NULL,那么就说明,n为长度len了。这种情况只需要将第一个节点删掉即可:head=head->next.


贴出代码:

solution:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {    int i=0;    int len=0;    struct ListNode* temp_head =head;    struct ListNode* result_head =head;            if (!head->next) return NULL;        for (i=0;i<n;i++) {        temp_head=temp_head->next;    }    if (!temp_head) return head->next;        while(temp_head->next) {        temp_head = temp_head->next;        result_head = result_head->next;    }    result_head->next = result_head->next->next;           return head;    }


阅读全文
0 0
原创粉丝点击