import com.demo.ListNode;
import java.util.EmptyStackException;
public class LLStack {
private ListNode headNode;
public LLStack(ListNode headNode) {
this.headNode = new ListNode(null);
}
public void Push(int data){
if (headNode == null){
headNode = new ListNode(data);
}else if (headNode.getNext() == null){
headNode.setData(data);
}else {
ListNode llNode = new ListNode(data);
llNode.setNext(headNode);
headNode = llNode;
}
}
public int top(){
if (headNode == null){
return -1;
}else {
return headNode.getData();
}
}
public int pop() {
if (headNode == null) {
throw new EmptyStackException();
}else{
int data = headNode.getData();
headNode = headNode.getNext();
return data;
}
}
public boolean isEmpty(){
if (headNode == null) {
return true;
}else{
return false;
}
}
public void deleteStack(){
headNode = null;
}
}
单向链表
public class ListNode {
private int data;
private ListNode next;
public ListNode(Integer data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public static int ListLength(ListNode headNode){
int length = 0;
ListNode headNodeS = headNode;
if (headNode != null){
length++;
headNodeS = headNode.getNext();
}
return length;
}
public static ListNode InsertInlinkedList(ListNode headNode,ListNode nodeToInsert,int position){
if (headNode == null){ // 若链表为空,插入
return nodeToInsert;
}
int size = ListLength(headNode); // 获取结点个数
if (position > size-1 || position < 1){
System.out.println(size+1);
return headNode;
}
if (position == 1){ // 在链表开头插入
nodeToInsert.setNext(headNode);
return nodeToInsert;
}else{
//在中间或结尾插入
ListNode previousNode = headNode;
int count = 1;
while (count < position - 1){
previousNode = previousNode.getNext();
count++;
}
ListNode currentNode = previousNode.getNext();
nodeToInsert.setNext(currentNode);
previousNode.setNext(nodeToInsert);
}
return headNode;
}
public static ListNode DeleteNodeFromlinkedList(ListNode headNode, int position){
int size = ListLength(headNode);
if (position > size || position < 1){
System.out.println(size);
return headNode;
}
if (position == 1){
ListNode currentNode = headNode.getNext();
headNode = null;
return currentNode;
}else { //删除中间或表尾结点
ListNode previousNode = headNode;
int count = 1;
while(count < position){
previousNode = previousNode.getNext();
count++;
}
ListNode currentNode = previousNode.getNext();
previousNode.setNext(currentNode.getNext());
currentNode = null;
}
return headNode;
}
public static void DeletelinkedList(ListNode headNode){
ListNode auxilaryNode, iterator = headNode;
while (iterator != null){
auxilaryNode = iterator.getNext();
iterator = null; //java垃圾回收器将自动处理
iterator = auxilaryNode;
}
char[] c = new char[10];
String s;
}
}



