package List;
class Lnode{
public int data;
public Lnode next;
public Lnode(int data){
this.data = data;
}
public Lnode(){
}
}
public class SingleLinkList {
Lnode head = new Lnode();
public void addNodeT(int e){ //尾插法
Lnode newNode = new Lnode(e);
Lnode p = head;
while(p.next!=null){
p = p.next;
}
p.next = newNode;
}
public void addNodeH(int e){ //头插法
Lnode newNode = new Lnode(e);
Lnode p=head;
newNode.next = p.next;
p.next = newNode;
}
public void print(){
Lnode p = head;
if(head == null){
System.out.print("链表为空");
}
else {
while (p.next != null) {
System.out.print(p.next.data + " ");
p = p.next;
}
}
System.out.println(" ");
}
public int size(){
int count = 0;
Lnode p = head;
if(head ==null){
return 0;
}
while(p.next!=null){
p = p.next;
count++;
}
return count;
}
public void clear(){
head = null;
}
public void reverseListByself(){
if (head.next==null||head.next.next==null){
return;
}
Lnode temp = head.next.next;
head.next.next=null;
while(temp != null){
Lnode cur = temp.next;
temp.next = head.next;
head.next = temp;
temp = cur;
}
} //原地反转单链表
public void reverseListByaddNodeH(){
Lnode newhead = new Lnode();
Lnode cur = newhead;
Lnode p = head;
while(p.next!=null){
Lnode newNode = new Lnode(p.next.data);
newNode.next = cur.next;
cur.next = newNode;
p = p.next;
}
head.next = newhead.next;
} //通过头插法反转单链表
public void bubbleSortList(){
if(head == null || head.next == null) //链表为空或者仅有单个结点
return ;
Lnode cur = head.next;
Lnode ter = null;
Lnode p = head;
while(cur!=ter){
while(cur.next!=ter){
if(cur.data<cur.next.data){
p = cur;
cur = cur.next;
}
else{
Lnode temp = cur.next;
cur.next = cur.next.next;
temp.next = cur;
p.next = temp;
p =temp;
}
}
ter = cur;
p = head;
cur = head.next;
}
} //单链表的排序(不改变节点值)
public static void main(String[] args) {
SingleLinkList linkList = new SingleLinkList();
// linkList.addNodeT(1);
// linkList.addNodeT(3);
// linkList.addNodeT(2);
// linkList.addNodeT(4);
// linkList.addNodeT(5);
linkList.addNodeH(1);
linkList.addNodeH(3);
linkList.addNodeH(2);
linkList.addNodeH(4);
linkList.addNodeH(5);
System.out.println("单链表长度为:"+linkList.size());
linkList.print();
// linkList.clear();
// linkList.print();
// System.out.println("单链表长度为:"+linkList.size());
// linkList.reverseListByaddNodeH();
// System.out.println("反转后的单链表为:");
linkList.bubbleSortList();
System.out.println("排序后的单链表为:");
linkList.print();
}
}
运行结果:
单链表长度为:5
1 2 3 4 5
单链表长度为:5
反转后的单链表为:
5 4 3 2 1
排序后的单链表为:
1 2 3 4 5