Remove Nth Node From End of List(鏈表,帶測試代碼)

Given a linked list, remove the nth node from the end of list and return its head.node

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

要求是一次過....看來基礎仍是有點差差的啊。spa

1.首先回顧一下鏈表的基本特性,從三點來分析下:3d

1> 存儲分配方式,鏈表用一組任意的存儲單元存放線性表的元素。指針

2>時間性能,查找O(n),插入和刪除,找出某位置指針後,插入和刪除時僅爲O(1)。調試

3>空間性能,不須要分配存儲空間,只要須要就能夠malloc,因此也叫動態鏈表。code

4> 插入和刪除節點圖示:blog

 

2.動態鏈表的建立(leedcode的鏈表是沒有頭結點),第一個形參參數是指針,要想改變指針的值,須要用引用或者指向指針的指針。ci

void CreateListHead(ListNode* &head, int n) 
{
    int j=0;
    head = (ListNode*)malloc(sizeof(ListNode));
    head->next=NULL;  
    head->val=v[j++];//v是用戶輸入的每一個節點的val
    ListNode* p=head;
    for (int i=1;i<n;++i)
    {
        ListNode* newNode;
        newNode = (ListNode*)malloc(sizeof(ListNode));
        p->next=newNode;
        newNode->next=NULL;  
        newNode->val=v[j++];
        p=p->next;
    }
}

3.全部調試代碼

struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
     };
class Solution {
public:
    int getLength(ListNode *head){
        int length=0;
        while(head){
            ++length;
            head=head->next;
        }
        return length;
    }
    void deleteNode(ListNode* &head,int loc)//第一個位置是1
    {
        if(loc==1){
            head=head->next;
        }
        else
        {
            ListNode* p=head;
            int j=1;
            while (p->next&&j<loc-1)
            {
                p=p->next;
                ++j;
            }
            p->next=p->next->next;
        }
    }
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if(head==NULL) 
            return NULL;
        ListNode* res=head;//須要新建局部變量
        int len=getLength(res);
        int loc=len-n+1;
        deleteNode(res,loc);
        return res;
    }
};
vector<int> v;
int num;
void CreateListHead(ListNode* &head, int n) 
{
    int j=0;
    head = (ListNode*)malloc(sizeof(ListNode));
    head->next=NULL;  
    head->val=v[j++];
    ListNode* p=head;
    for (int i=1;i<n;++i)
    {
        ListNode* newNode;
        newNode = (ListNode*)malloc(sizeof(ListNode));
        p->next=newNode;
        newNode->next=NULL;  
        newNode->val=v[j++];
        p=p->next;
    }
}
int main()
{
    freopen("C:\\Users\\Administrator\\Desktop\\test.txt","r",stdin);
    cin>>num;
    for (int i=0;i<num;++i)
    {
        int temp;
        cin>>temp;
        v.push_back(temp);
    }
    ListNode* head=NULL;
    CreateListHead(head,num);
    Solution so;
    ListNode* res=so.removeNthFromEnd(head,1);
    return 0;
}
相關文章
相關標籤/搜索