码迷,mamicode.com
首页 > 编程语言 > 详细

单链表算法实现

时间:2018-08-01 23:54:26      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:let   lin   算法   out   dex   his   lse   bool   this   

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());
}


}

单链表算法实现

标签:let   lin   算法   out   dex   his   lse   bool   this   

原文地址:https://www.cnblogs.com/fuyusong/p/9404375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!