链表的相应操作

来源:互联网 发布:mac os 重装系统 编辑:程序博客网 时间:2024/05/21 12:42

一,目的
本节内容主要包括链表的排序,以及两个单链表的合并。

二,分析。
在对链表排序的时候,可以采用选择排序等方法,对比原来的对数进行排序,此时的不同便是如今要对结点进行排序。

而合并两个单链表,前提是两个单链表是有序的,这样合并完的单链表便也是有序的。

三,代码实现

struct Node{    int _data;    Node* _next;    Node(const int& x)        :_data(x), _next(NULL)    {    }};
Node* Selete_Sort(Node* head)  //选择排序{    if (head == NULL || head->_next == NULL)        return head;    Node* x, *y;    for (x = head; x!= NULL; x = x->_next)    {        Node* temp = x;        for (y = x->_next; y != NULL; y = y->_next)        {            if (y->_data < temp->_data)                swap(temp, y);        }        if (temp != x)            swap(x->_data, temp->_data);    }    return head;}
Node* Bubble_Sort(Node* head) //冒泡排序,很巧妙的实现{    Node* cur = head;    Node* tail = NULL;    while (cur != tail)    {        while (cur->_next != tail)        {            if (cur->_data > cur->_next->_data)                swap(cur->_data, cur->_next->_data);            cur = cur->_next;        }        tail = cur;        cur = head;    }    return head;}
template<class T>Node<T>* sortTwoList(Node<T>* a, Node<T>* b) //递归实现合并两个有序单链表{    if (a == NULL)        return b;    if (b == NULL)        return a;    typedef Node<T> node;    node* temp;    if (a->data < b->data)    {        temp = a;        temp->_next = sortTwoList(a->_next, b);    }    else    {        temp = b;        temp->_next = sortTwoList(a, b->_next);    }    return temp;}
template<class T>Node<T>* sortTwoList1(Node<T>* a, Node<T>* b) //非递归实现{    if (a == NULL)        return b;    if (b == NULL)        return a;    Node<T>* x=a;    Node<T>* y=b;    Node<T>* cur = new Node<int>(-1); //创建一个头结点    Node<T>* temp = cur;    while (x!= NULL || y!= NULL)    {        while(x && x->data <= y->data)        {            temp->_next = x;            x = x->_next;            temp = temp->_next;        }        if (x == NULL && y) //出来之后一定要先判空,而且要直接return,不然进入别的循环,会出现空指针的情况        {            while (y)            {                temp->_next = y;                y = y->_next;                temp = temp->_next;            }            return cur->_next;        }        while (y&& y->data < x->data)        {            temp->_next = y;            y = y->_next;            temp = temp->_next;        }        if (y == NULL && x)            {                while (x)                {                    temp->_next = x;                    x = x->_next;                    temp = temp->_next;                }                return cur->_next;            }}

四,总结

好多代码面试时都要求手写代码的,然后我机写还是出了bug,还是太差,好好努力吧,把内容放到博客里,没事了可以看一下。

原创粉丝点击