LeetCode 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.

解题思路:

       本题即为链表的删除操作。为了使得针对头结点的操作更加简便,所以首先在head前建立一个新的头结点。由于是删除从尾结点开始的第n个结点,所以首先要知道链表中结点的数目,之后计算出要删除的结点即为从首节点开始的第L-n+1(L为链表的长度)个结点。(实现如代码一所示)

      由于题目要求Try to do this in one pass,所以代码一显得繁琐一些,可以直接令一个指针tmp指向自己设置的头节点,然后首先向后移动n+1个位置,当tmp指针指向NULL时,pre变为要删除结点的前一个结点,之后进行删除操作即可。(实现如代码二所示)



代码展示

class Solution {
public:
    //代码一
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode dummy = ListNode(0);
        dummy.next = head;
        int i=-1 ;
        ListNode* tmp =  &dummy;
        for(;tmp!=NULL;i++)
            tmp = (*tmp).next;
        int j = i-n;
        tmp = &dummy;
        while(j--)
        {
            tmp = (*tmp).next;
        }
        ListNode * ans = (*tmp).next;
        (*tmp).next=(*ans).next;
        return dummy.next;
        
    }
};


 
  

class Solution {
public:
    //代码二
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode dummy = ListNode(0);
        dummy.next = head;
        //int i=-1 ;
        ListNode* tmp =  &dummy;
        ListNode* pre =  &dummy;
        for(int i=0;i<=n;i++)
            tmp = (*tmp).next;
        while(tmp!=NULL)
        {
            tmp= (*tmp).next;
            pre= pre->next;
        }
        (*pre).next = (*(*pre).next).next;
        return dummy.next;
        
    }
};



你可能感兴趣的:(leetcode)