1.node节点
链表是一种递归的数据结构,他为空或者指向一个节点的引用,该节点有一个泛型元素何指向另一条链表的引用
链表实现栈(下压堆栈)
package lianbaioTest;
import javax.xml.soap.Node;
public class Stack <String>{
private Node first;
private int N;
private class Node{
String s;
Node next;
}
public boolean isEmpty(){
return first==null;
}
public int size(){
return N;
}
//向栈顶增加元素
public void push(String s){
Node old=first;
first=new Node();
first.s=s;
first.next=old;
N++;
}
//从栈顶弹出元素
public String pop(){
String x=first.s;
first=first.next;
N--;
return x;
}
}
链表实现队列
package lianbaioTest;
import javax.xml.soap.Node;
public class Queue <Item>{
private Node first;
private Node last;
private int N;
private class Node{
Item item;
Node next;
}
public boolean isEmpty(){
return first==null;
}
public int size(){
return N;
}
//向表尾增加元素
public void enqueue(Item item){
Node old=last;
last=new Node();
last.item=item;
last.next=null;
if(isEmpty()){
first=last;
}
else {
old.next = last;
}
N++;
}
//从表头删除元素
public Item dequeue(){
Item item=first.item;
first=first.next;
if(isEmpty()){
last=null;
}
N--;
return item;
}
}
链表的基本操作
package lianbaioTest;
import javax.xml.soap.Node;
public class KinkedList {
private Node first;
private Node last;
private class Node{
int data;
Node next;
}
public boolean isEmpty(){
return first==null;
}
//创建链表
public void add(int[] a){
for(int i=0;i<a.length;i++){
Node old=last;
last=new Node();
last.data=a[i];
if(isEmpty()){
first=last;
}
else {
old.next = last;
}
}
}
//删除第k个节点
public boolean deOne(int k){
if(k==1){
first=first.next;
}
else{
int i=2;
Node preNode=first;
Node curNode=first.next;
while(curNode!=null){
if(k==i){
preNode.next=curNode.next;
return true;
}
else{
preNode=preNode.next;
curNode=curNode.next;
i++;
}
}
}
return false;
}
//排序
public void order(){
Node curNode=first;
int temp;
while(curNode.next!=null) {
Node nextNode = curNode.next;
while (nextNode != null) {
if (curNode.data > nextNode.data) {
temp = curNode.data;
curNode.data = nextNode.data;
nextNode.data = temp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
}
//打印链表
public void sout(){
Node head=first;
while(head!=null){
System.out.print(head.data);
head=head.next;
}
}
}