标签:
唉,说点废话,昨天偶尔看到一年前自己用C解约瑟夫环问题的循环链表,唏嘘不已,想想自己一年前嵌入式的梦呢,这两天发生了许多,而有些人不在了就真的不在了,心情不好,不多说了,直接上代码,只是些链表的基本操作,花些功夫看就好了。
首先,建立一个Node类,里面内构一个Node对象和数据(用来区分);
public class Node { protected Node next; //指针 protected int data; //数据 public Node(int data){ this.data = data; } //显示节点 public void display(){ System.out.println(data+" "); } }
然后创建一个LinkList类,里面包含了链表的一些基本方法,
public class LinkList { public Node first; //定义一个头结点 public LinkList(){ this.first = null; } //插入一个头结点 public void addFirstNode(int data){ Node node = new Node(data); node.next = first; first = node; } //删除一个头节点,并返回头结点 public Node deleteFirstNode(){ Node tempNode = first; first = tempNode.next; return first; } //在替换掉index后面的节点。 public void add(int index , int data){ Node node = first; Node current = first; while(index-->0){ current = node.next; node = current; } current.data = data; } //在第index节点后面插入节点 public void Insert(int index , int data){ Node node = new Node(data); Node current = first; Node privious = first; while(index-->0){ privious = current; current = current.next; } node.next = current; privious.next = node; } //删除任意位置的节点 public void delete(int index){ Node current = first; Node privious = first; while(index-->0){ privious = current; current = current.next; } if(current == first){ first = first.next; }else{ privious.next = current.next; } } //根据data的值删除节点,删除找到的第一个节点 public void deleteData (int data){ Node privious = first; Node current = first; while(current.data!=data){ privious = current; current = current.next; } if(current == first){ first = first.next; }else{ privious.next = current.next; } } }
再建立一个主类,
public class TestLink { public static void main(String[] args){ LinkList l = new LinkList(); l.addFirstNode(1); l.addFirstNode(2); l.addFirstNode(3); Node node = l.first; l.Insert(2, 5); l.deleteData(5); while(node!=null){ node.display(); node = node.next; } } }
实在是没有心情继续写了,希望以后会好点,2015年8月9日18:55分。
标签:
原文地址:http://www.cnblogs.com/xiangxi/p/4716045.html