链表穿针

把链表A1->A2->A3…->An变成A1->An->A2->An-1…

#include 
#include 
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x):val(x),next(NULL){}
};


/*A1->A2->A3...->An A1->AN->A2->An-1->...*/
ListNode* func(ListNode *head)
{
    if (head == NULL || head->next == NULL)
        return head;
    deque dq;
    ListNode* p = head;
    ListNode* next = NULL;
    while(p != NULL)
    {
        next = p->next;
        p->next = NULL;
        dq.push_back(p);
        p = next;
    }
    ListNode* new_head = dq.front();
    dq.pop_front();
    ListNode* p_front = NULL;
    ListNode* p_back = NULL;
    ListNode* last = new_head;
    int front2back = 1;
    while(!dq.empty())
    {
        p_front = dq.front();
        p_back  = dq.back();
        if (p_back != p_front)
        {
            if(front2back)
            {
                last->next = p_back;
                dq.pop_back();
                front2back = 0;
                last = p_back;
            }
            else
            {
                last->next = p_front;
                dq.pop_front();
                front2back = 1;
                last = p_front;
            }
        }
        else
        {
            last->next = p_front;
            dq.pop_back();
        }
    }
    return new_head;
}


void print_list(ListNode*head)
{
    ListNode *p = head;
    while(p)
    {
        cout<val;
        if (p->next)
            cout<<"->";
        p = p->next;
    }
    cout <next = new_node;
        pre = new_node;
    }
    print_list(head);
    ListNode* head1 = func(head);
    print_list(head1);
    //TODO delete []
    return 0;
}

你可能感兴趣的:(数据结构与算法,数据结构与算法)