单链表算法实现
Posted fuyusong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单链表算法实现相关的知识,希望对你有一定的参考价值。
class Node {
Node next = null;
int data;
public Node(int data){
this.data = data;
}
}
public class MyLinkedList {
Node head = null;
public void addNode(int d){
Node newNode = new Node(d);
if (head == null) {
head = newNode;
return;
}
Node tmp = head;
while(tmp.next != null){
tmp = tmp.next;
}
tmp.next = newNode;
}
public Boolean deleteNode(int index){
if(index < 1|| index > length()){
return false;
}
if(index == 1){
head = head.next;
return true;
}
int i = 1;
Node preNode = head;
Node curNode = preNode.next;
while(curNode != null){
if(i == index){
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i++;
}
return true;
}
public Node orderList(){
Node nextNode = null;
Node curNode = head;
int temp = 0;
while(curNode.next != null){
nextNode = curNode.next;
while(nextNode != null){
if (curNode.data > nextNode.data) {
temp = curNode.data;
curNode.data = nextNode.data;
nextNode.data = temp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
return head;
}
public int length(){
int length = 0;
Node tmp = head;
while(tmp != null){
length++;
tmp = tmp.next;
}
return length;
}
public void printList(){
Node tmp = head;
while(tmp != null){
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public static void main(String[] args){
MyLinkedList list = new MyLinkedList();
list.addNode(5);
list.addNode(3);
list.addNode(1);
list.addNode(3);
System.out.println("list:");
list.printList();
System.out.println(list.length());
}
}
以上是关于单链表算法实现的主要内容,如果未能解决你的问题,请参考以下文章