java 实现
/**
* Created by duia on 2018/5/4.
* 链表实现队列
*/
public interface IQueue<T> {
/**
* 入队
* @param data
*/
public abstract void push(T data);
/**
* 出队
* @return
*/
public abstract T pop();
}
/**
* Created by duia on 2018/5/4.
*/
public class QueueImp<T> implements IQueue<T> {
/**
* 队列头指针
*/
private Node<T> mHead;
/**
* 队列尾指针
*/
private Node<T> mTail;
@Override
public void push(T data) {
//头指针为null说明是空队列
if(null == mHead){
mHead = mTail;
}
Node<T> node = new Node<>();
node.obj = data;
if(null != mTail){
mTail.next = node;
}
mTail = node;
}
@Override
public T pop() {
if(mHead == null){
return null;
}
Node<T> temp = mHead;
T ret = mHead.obj;
mHead = mHead.next;
temp = null;
return ret;
}
}
测试
public static void main(String[] args) {
QueueImp<Integer> integerQueueImp = new QueueImp<>();
integerQueueImp.push(1);
integerQueueImp.push(2);
integerQueueImp.push(3);
Integer current = integerQueueImp.pop();
while (null != current){
System.out.println(current);
current = integerQueueImp.pop();
}
}
c++ 实现
#include <iostream>
using namespace std;
typedef int dataType;
typedef struct Node{
dataType data;
struct Node *next;
}HaHa,*pointer;
pointer head,tail;
void push23(dataType data);
dataType pop23();
int main()
{
//using namespace std;
//sayHello();
//cout << "hello" << endl;
//sayHehe();
//int arr[8] = {1,2,3,4,5,6,7,8};
//sum_arr(arr + 2, arr + 5);
if (NULL == head)
{
head = tail;
cout << "hahha" << endl;
}
push23(1);
push23(2);
push23(3);
int current = pop23();
while(-1 != current)
{
printf("%d\n", current);
current = pop23();
}
cout << "hello world!" << endl;
return 0;
}
void push23(dataType data)
{
HaHa *node = new HaHa();
node->data = data;
if (NULL == head)
{
head = tail = node;
}else{
tail->next = node;
tail = node;
}
}
dataType pop23()
{
if (head == NULL)
{
return -1;
}
Node* temp = head;
head = head->next;
dataType ret = temp->data;
delete temp;
return ret;
}