5.14-Stacks and Queues

232.Implement Queue using Stacks

push(x)
pop()
peek()
empty()

思路:
先考虑使用哪种数据结构? -> 链表,
stack和queue的区别? -> stack的链表结构有一个指针(first), queue的链表结构有两个指针(first + last)。
如何将FILO顺序转换为FIFO顺序?两个栈实现一个队列现用push将所有元素都压入1号栈,然后用pop() 将所有的元素都从一号栈中拿出,压入2号栈中,2号栈中的元素与1号栈中的元素排列顺序相反(1号栈为FILO,2号栈为FIFO), 2号栈中元素排列顺序与queue中排列顺序一致。实现queue
MyQueue() {} 的构造器如何实现? ->

Q: 如何保证push栈和pop栈相互之间有序,不混乱?
A: 添加if statement

unclosed character literal ?
A: In java, single quote can only take one character

  1. Palindrome Linked List
    题目: 给定一个链表,判断是否是回文链表

思路:
一个头指针,一个尾指针,相向移动,不断匹配,对于奇数个元素,若除middle元素外其他元素全部都相同,对于偶数个元素,若全部匹配,则为回文链表,否则非回文。

Q: what is the difference between left.next = head; left = left.next and leftHead.next = head; left = left.next if left = leftHead ?
A: In a while loop, left.next would be updated during every loop, so, leftHead.next = head and left.next = head are same if this assignment is the first assignment. But when the loop start going, then there would be a Null pointer exception. Because the left.next do not be updated in leftHead.next = head, but it was be used in left = left.next.

posted @ 2018-05-16 06:30  AugusKong  阅读(167)  评论(0编辑  收藏  举报