本来该学习java链表源码了,在学习源码之前先复习一下java的链表知识
下面是java操作链表的几个简单例子:
先定义一个Node的类
public class Node {
private int record;//变量
private Node nextNode;//
public Node(){
}
public Node(int record){
this.record = record;
}
public int getRecord() {
return record;
}
public void setRecord(int record) {
this.record = record;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}
自己写的链表工具类
public class Linked {
private static int count = 0;//用来记录链表的长度
public static void main(String [] args){
//构造哟个含有元素的链表
Node head = new Node();
Node temp = null;//临时节点
Node cur = null;//当前结点
for(int i=1;i<10;i++){
temp = new Node(i);
if(i != 1){//说明不是头节点
cur.setNextNode(temp);
}else{//是头节点
head.setNextNode(temp);
}
cur = temp;
count++;
}
Node before = head;
while(before != null){
System.out.println(before.getRecord());
before = before.getNextNode();
}
System.out.println("count"+count);
}
//向链首添加一个元素
public static Node AddToHead(Node head,int value){
Node newNode = new Node(value);
if(null == head)//当传进来的head为空也就是说链表不存在
{
head = newNode;//新生成的节点作为头节点
return head;
}
newNode.setNextNode(head.getNextNode());//把头节点之后的第一个节点赋值给newNode
head.setNextNode(newNode);
count++;
return head;
}
//向链尾添加一个元素
public static Node AddToTail(Node head,int value){
Node newNode = new Node(value);
if(null == head){
head = newNode;
return head;
}
//遍历到最后一个节点
while(head.getNextNode()!= null)
{
head = head.getNextNode();
}
//把最后的一个节点的元素置为newNode
head.setNextNode(newNode);
count++;
return head;
}
//删除一个元素,并返回所删除元素的data
public static int remove(Node head,int index){
if(null == head)return -1;
int counts = 0;
while(head.getNextNode()!= null){
++counts;
if(counts == index)//跳出循环时指针指向index-1的位置
break;
head = head.getNextNode();
}
//此时head是要删除元素的前一个元素
if(counts < index)//说明链表的长度小于index
return -1;
int elem = head.getNextNode().getRecord();
head.setNextNode(head.getNextNode());
count --;
return elem;
}
//倒着输出链表,两种方式1:先把链表反转,在输出 2:把值存入栈中。采用第二种
public static Stack<Integer> printReverse(Node head){
Stack<Integer> nodeStack = new Stack<Integer>();
if(head == null){
nodeStack.push(-1);
return nodeStack;
}
while(head.getNextNode()!= null){
nodeStack.push(head.getNextNode().getRecord());
head = head.getNextNode();
}
return nodeStack;
}
//反转链表
public static Node Reverse(Node head){
if(null == head){
return head;
}
Node pre = head;
Node cur = head.getNextNode();
Node next;
while(null != cur){
next = cur.getNextNode();
cur.setNextNode(pre);
pre = cur;
cur = next;
}
head.setNextNode(null);
head = pre;
return head;
}
}