/*
*@program: algStudy
*@description: 环形链表实现的Queue, 只使用一个last指针
*@author: chensy
*@create: 2019-07-13 13:36
*/
public class LinkedListDeQueue
{
private ListNode last;
private int size = 0;
public LinkedListDeQueue() {
this.last = new ListNode(-1);
}
/*
* @Author chensy
* @Description //TODO 插入到链表尾部, 返回插入值
* @Date 13:54 2019/7/13
* @Param [data]
* @return int
**/
public int push (int data){
ListNode tmpHeadNode;
if(size == 0) {
tmpHeadNode = new ListNode(data);
last.next = tmpHeadNode;
}else{
// get head
tmpHeadNode = last.next;
//last -> data
last.next = new ListNode(data);
}
// data -> head
last.next.next = tmpHeadNode;
// last = data
last = last.next;
size++;
return data;
}
public int pop() {
if(size <= 0)
{
throw new IndexOutOfBoundsException("当前队列为空"); //int 最小值
}
ListNode tmpHead = last.next;
ListNode tmpCurrentNode = tmpHead;
//取倒数第二个
while(tmpCurrentNode.next.next != tmpHead )
{
tmpCurrentNode = tmpCurrentNode.next;
}
size--;
//假若只有一个值时
if(tmpCurrentNode.next == tmpHead)
{
int currentData = last.data;
last = new ListNode(-1);
return currentData;
}
//将倒数第二个的指针指向头
int lastData = last.data;
last = tmpCurrentNode;
tmpCurrentNode.next = tmpHead;
return lastData;
}
//遍历链表
public void printfLinkedListDeQueue() {
if(last == null)
{
System.out.println("链表为空");
return ;
}
ListNode tmpHead = last.next;
ListNode tmpCurrentPointer = tmpHead;
while (tmpCurrentPointer.next != tmpHead)
{
if(tmpCurrentPointer == tmpHead){
System.out.print("[ " + tmpHead.data + ", ");
}else{
System.out.print(tmpCurrentPointer.data + ", ");
}
tmpCurrentPointer = tmpCurrentPointer.next;
}
if(size == 1)
{
System.out.print("[ " + tmpHead.data + " ] ");
return;
}
System.out.print(tmpCurrentPointer.data + " ]");
}
}