DS单链表--结点交换

#include <iostream>
using namespace std;
class ListNode
{
public:
    int data;
    ListNode *next;
    ListNode()
    {
        next = NULL;
    }
};
class linklist
{
public:
    ListNode *head;
    int len;
    linklist()
    {
        head = new ListNode;
        len = 0;
    }
    void createlist(int n)
    {
        int i;
        ListNode *q = head;
        for(i = 0; i < n; i++)
        {
            ListNode *p = new ListNode();
            cin >> p->data;
            q->next = p;
            q = p;
        }
        len = n;
        display();
    }
    void display()
    {
        ListNode *p = head->next;
        while(p)
        {
            cout << p->data << " ";
            p = p->next;
        }
        cout << endl;
    }
    ListNode *index(int i)
    {
        int k;
        ListNode *p = head;
        if(i != 0)
        {
            for(k = 1; k < i; k++)
            {
                p = p->next;
            }
            return p->next;
        }
        else
        {
            return head;
        }
    }
    void swap(int x, int y)
    {
        if(x >= 1 && x <= len && y >= 1 && y <= len)
        {
                ListNode *p = index(x-1);
                ListNode *q = p->next;
                ListNode *r = index(y-1);
                ListNode *s = r->next;
                ListNode *m = q->next;
                r->next = q;
                q->next = s->next;
                p->next = s;
                s->next = m;
                display();
        }
        else cout << "error" << endl;
    }
};
int main()
{
    int n, x, y;
    cin >> n;
    linklist ll;
    ll.createlist(n);
    cin >> x >> y;
    ll.swap(x, y);
    cin >> x >> y;
    ll.swap(x, y);
    return 0;
}

 

相关文章: