常见的一些算法

一、单链表反转

    1,先定义一个节点类。

public class Node {
    int index;
    Node next;

    public Node(int index, Node next) {
      this.index = index;
      this.next = next;
    }
  }

迭代法实现。先将下一节点纪录下来,然后让当前节点指向上一节点,再将当前节点纪录下来,再让下一节点变为当前节点

public Node reverse(Node node) {
    Node prev = null;
    Node now = node;
    while (now != null) {
      Node next = now.next;
      now.next = prev;
      prev = now;
      now = next;
    }

    return prev;
  }

二、两个栈实现一个队列

思路:入队时,直接压入stack1中

           出队时,判断stack2是否为空,如果stack2为空,则将stack1中的元素倒入stack2中,否则直接弹出stack2中的元素

//入队操作
void EnQueue(stack<int> &s1,stack<int> &s2,int m)
{
    s1.push(m);
}

//出队操作
void DeQueue(stack<int> &s1,stack<int> &s2,int &m)
{
    if (s2.empty())
    {
        int p = s1.size();
        for (int i=0;i<p;i++)
        {
            s2.push(s1.top());
            s1.pop();
        }    
    }
    m = s2.top();
    s2.pop();
}

三、两个队列实现一个栈

将queue1用作进栈出栈,queue2作为一个中转站

入栈时,直接压入queue1中

出栈时,先将queue1中的元素除最后一个元素外依次出队列,并压入队列queue2中,将留在queue1中的最后一个元素出队列即为出栈元素,最后还要把queue2中的元素再次压入queue1中

实现代码如下:

//进栈操作
void stackpush(queue<int> &q1,queue<int> &q2,int m)
{
    q1.push(m);
}

//出栈操作
void stackpop(queue<int> &q1,queue<int> &q2,int &m)
{
    int p = q1.size();
    for (int i=0;i<p-1;i++)
    {
        q2.push(q1.front());
        q1.pop();
    }
    m = q1.front();
    q1.pop();
    int l = q2.size();
    for (int j = 0;j<l;j++)
    {
        q1.push(q2.front());
        q2.pop();
    }
}

四、快速排序

算法描述:对于一组给定的记录,通过一趟排序后,将原序列分为两部分,其中前一部分的所有记录均比后一部分的所有记录小,然后再依次对前后两部分的记录进行快速排序,递归该过程,直到序列中的所有记录均有序为止。

/**
 * 快速排序
 * 平均O(nlogn),最好O(nlogn),最坏O(n^2);空间复杂度O(nlogn);不稳定;较复杂
 * @author zeng
 *
 */
public class QuickSort {
 
    public static void sort(int[] a, int low, int high) {
        if(low>=high)
            return;
        int i = low;
        int j = high;
        int key = a[i];
        while (i < j) {
            while (i < j && a[j] >= key)
                j--;
            a[i++] = a[j];
            while (i < j && a[i] <= key)
                i++;
            a[j--] = a[i];
        }
        a[i] = key;
        sort(a,low,i-1);
        sort(a,i+1,high);
    }
 
    public static void quickSort(int[] a) {
        sort(a, 0, a.length-1);
        for(int i:a)
            System.out.print(i+" ");
    }
 
    public static void main(String[] args) {
        int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };
        quickSort(a);
    }
}

猜你喜欢

转载自www.cnblogs.com/qinaidexin/p/11736600.html