十六週

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.

給出n,刪除鏈表中倒數第n個元素

先遍歷鏈表得到鏈表大小,再減去n得到需要刪除的元素位置。

 ListNode* removeNthFromEnd(ListNode* head, int n) {
        int pos=1;
        ListNode* size=head;
        while(size->next!=NULL)
        {
            size=size->next;
            pos++;
        }

        if(n==pos)
        {
            head=head->next;
            return head;
        }
        else
        {
            int i=1;
            ListNode* node=head;
            while(i<pos-n)
            {
                node=node->next;
                i++;
            }
            node->next=node->next->next;
            return head;
        }
    }

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

將鏈表中的每兩個元素調換位置。注意:1.不能直接更改元素值。2.不用佔用新的空間。

每兩個元素爲一組調換順序。注意:
1.第一組調換順序後要更改head的位置。
2.當有奇數個元素時最後一個不用翻轉。

  ListNode* swapPairs(ListNode* head) {
        if(head==NULL||head->next==NULL)
            return head;
        ListNode* pos=head;
        while(pos!=NULL&&pos->next!=NULL)
        {
            if(pos==head)
            {
                ListNode* second=pos->next;
                pos->next=second->next;
                second->next=pos;
                head=second;
            }
            else
            {
                ListNode* first=pos->next;
                ListNode* second=pos->next->next;
                if(second==NULL)
                    break;
                else
                {
                    first->next=second->next;
                    second->next=first;
                    pos->next=second;
                    pos=first;
                }
            }
        }

        return head;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章