单向链表
来源:互联网 发布:阿里云空间不足 编辑:程序博客网 时间:2024/06/06 13:20
单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始。
[编辑]动态单链表单向链表的数据结构可以分为两部分:数据域和指针域,数据域存储数据,指针域指向下一个储存节点的地址。
package linklist2;
public class LinkList {
private Node firstNode;
private int length;
public LinkList(){
clear();
}
public void clear(){
firstNode=null;
length=0;
}
public Node getFirstNode(){
return firstNode;
}
public boolean add(int data){
Node node=new Node(data);
if(isEmpty()){
firstNode=node;
}else{
Node lastNode=getNodeAt(length);
lastNode.next=node;
}
length++;
return true;
}
public boolean isEmpty(){
//return length==0;
//use assert to get more details when error occurs
boolean result;
if(length==0){
assert firstNode==null;
result=true;
}else{
assert firstNode!=null;
result=false;
}
return result;
}
public void reverse(){
if(firstNode==null)return;
Node p=firstNode;//use p to traverse every node
Node previous=null;
while(p.next!=null){
Node q=p.next;// save p.next first because the next sentence changes p.next
p.next=previous;
previous=p;
p=q;
}
p.next=previous;
firstNode=p;//should not be ignored
}
//recursive
public Node reverseRecursive(Node p){
if(p==null)return null;
if(p.next==null){
firstNode=p;
return p;
}
Node q=p.next;
//reverse the remaining nodes,except p
//when recursive returns,you can regard the link as a link that has just two elements: p-->q
//so the last reversing is simple: q.next=p;p.next=null;
Node ph=reverseRecursive(q);
q.next=p;
p.next=null;
System.out.print("("+ph.data+")");//ph.data=1,always
return ph;
}
public void display(){
Node node=firstNode;
while(node!=null){
System.out.print(node.data+" ");
node=node.next;
}
System.out.println();
}
private Node getNodeAt(int position){
Node re=firstNode;
if(!isEmpty()&&position>1&&position<=length){
for(int count=1;count<position;count++){
re=re.next;
}
}
return re;
}
//use inner class
private class Node{
private int data;
private Node next;
private Node(int data){
this.data=data;
next=null;
}
}
}
----------------
测试一下哦
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkList list=new LinkList();
int[] a={1,2,3,4,5};
for(int each:a){
list.add(each);
}
list.display();
list.reverse();
list.display();
list.reverseRecursive(list.getFirstNode());
list.display();
}
- 单向链表
- 单向链表倒序
- 单向链表
- 单向链表逆转
- 逆转单向链表
- 单向链表反转
- 单向链表
- 单向链表(ZT)
- 反转单向链表
- 单向链表反转
- 单向链表
- 创建单向链表
- 单向链表反转
- 单向链表
- 单向链表
- 单向链表
- 单向链表
- C++ 单向链表
- android 开发报错处理
- php之日期函数(1)
- JavaScript获取元素在浏览器画布中的绝对位置 兼容IE6
- 引用式样式表
- python中调用C++写的动态库
- 单向链表
- 给安装文件设定条件
- com.microsoft.sqlserver.jdbc.SQLServerException: 结果集已关闭
- 堆栈与堆的区别
- JS 用div 覆盖 html元素
- 检测内存泄露的工具
- 自增运算
- meta标签
- JS 滚动到页面顶部 兼容 IE6/8、FF及webkit