数据结构-List
自制“火车结构”(链表)
public class MyList
{
//----------------------------------------------------------------------
class Cell
{
String data;
Cell next; // 这是指针,不是对象
public Cell(String x)
{
data = x;
next = null;
}
}
//-----------------------------------------------------------------------
private Cell _head; // 指向第一节车厢的指针(不是对象)
// 直奔主题,考虑一般情况
// 再处理特殊
public Cell getTail()
{
if(_head==null) return null;
Cell p = _head;
while(true){
if(p.next==null) break;
p = p.next;
}
return p;
}
public void add(String x)
{
//1.创建新车厢
Cell p = new Cell(x);
//2.找到尾车厢
Cell tail = getTail();
//3.挂接
if(tail==null)
_head = p; // 让_head 指向 p 所指向的东西
else
tail.next = p;
// 让 tail 所指向的对象的next 指向 p 所指向的对象
}
public int size()
{
Cell p = _head;
int n = 0;
while(true){
if(p==null) break;
p = p.next;
n++;
}
return n;
}
public String get(int k)
{
Cell p = _head;
for(int i=0; i<k; i++){
p = p.next;
}
return p.data;
}
public static void main(String[] args)
{
MyList a = new MyList();
a.add("abcd");
a.add("123456");
a.add("xyz");
a.add("rpq");
a.add("中国");
for(int i=0; i<a.size(); i++){
System.out.println(a.get(i));
}
}
}
//----------------------------------------------------
自定义栈结构
public class MyStack
{
private String[] buf;
private int num;
public void push(String x)
{
buf[num] = x;
num++;
}
public String pop()
{
if(isEmpty()) return null;
num--;
return buf[num];
}
public boolean isEmpty()
{
return num==0;
}
public MyStack()
{
buf = new String[100];
num = 0;
}
//应用
public static void main(String[] args)
{
String s = ".....(.....[......].....)...)..{.....[....]...}";
MyStack a = new MyStack();
boolean tag = true; // 假设匹配
for(int i=0; i<s.length(); i++){
char x = s.charAt(i);
if(x=='(') a.push(")");
if(x=='[') a.push("]");
if(x=='{') a.push("}");
if(x==')' || x==']' || x=='}'){
if(a.isEmpty()){
tag = false;
break;
}
char c = a.pop().charAt(0); // 弹出的字符
if(c!=x){
tag = false;
break;
}
}
}
if(!a.isEmpty()) tag = false;
System.out.println(tag);
/*
MyStack a = new MyStack();
a.push("abc");
a.push("1234");
a.push("xyz");
a.push("rpq");
a.push("中国");
while(!a.isEmpty()){
System.out.println(a.pop());
}
*/
}
}
浙公网安备 33010602011771号