package stackandqueue.stack.link;
public class MyLink {
Node head = null;
class Node{
private int val;
private Node next;
public Node(int val) {
this.val = val;
}
}
public void addNode(int val) {
Node node = new Node(val);
if (head == null) {
head = node;
return;
}
Node tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = node;
}
public int length() {
int i = 0;
if (head != null) {
i++;
}
Node tmp = head;
while (tmp != null) {
i++;
tmp = tmp.next;
}
return i;
}
public Boolean delNode(Integer index) {
if (index < 1 || index > length()) {
System.err.println("位置错误");
return false;
}
if (index-1 == 0) {
head = head.next;
return true;
}
Node tmp = head;
int i = 1;
while (tmp.next != null) {
i++;
if (i == index) {
tmp.next = tmp.next.next;
return true;
}
tmp = tmp.next;
}
return false;
}
public Boolean addNodeByIndex(int index,Integer val) {
Node newNode = new Node(val);
if (head == null) {
head = newNode;
return true;
}
if (index-1 == 0) {
newNode.next = head;
head = newNode;
return true;
}
Node tmp = head;
int i = 1;
while (tmp != null) {
i++;
if (i == index) {
newNode.next = tmp.next;
tmp.next = newNode;
return true;
}
tmp = tmp.next;
}
return false;
}
public void printNode() {
Node tmp = head;
while (tmp != null) {
System.err.print(tmp.val + "-");
tmp = tmp.next;
}
}
public static void main(String[] args) {
MyLink myLink = new MyLink();
myLink.addNode(4);
myLink.addNode(6);
myLink.addNode(2);
myLink.addNode(5);
myLink.addNode(9);
myLink.printNode();
System.err.println();
myLink.addNodeByIndex(1,0);
myLink.printNode();
}
}
|