您的位置:首页 > 其它

实现一个 链表 有序插入新节点

2012-11-08 00:52 435 查看
简述:

用Java实现一个链表,每次插入后都会进行插入排序,找到合适的位置,维护有序性

注意:

在新加入节点newNode(E v)函数实现时,

1)要判断,pHead是否为空,

2)要先和第一个头结点比较,如果比头结点还小,就插在头结点前面,同时更改头结点指针,

3)链表遍历的时候,一定不能忘记是用currentNode.next == null为结束条件的

4)遍历另外一个约束条件是,插入的节点要大于当前遍历到的节点,同时又要小于之后的那个节点,为了方便插入要保留前一个节点的指针,这样才能顺利插入,不然如果是保留后面一个节点的指针,就没法插入了

代码:

package data_structure;

class Node<E extends Comparable<E>>{
Node(){}
Node(E v){
value = v;
}
E value;
Node<E> next;
}

public class SortedLinkedList<E extends Comparable<E>> {
Node<E> pHead;
SortedLinkedList(){
pHead = null;
}
void newNode(E v){
if(pHead == null)
pHead = new Node<E>(v);
else{
if(v.compareTo(pHead.value) < 0){
Node<E> newNode = new Node<E>(pHead.value);
newNode.next = pHead.next;
pHead.next = newNode;
pHead.value = v;
return;
}
Node<E> currentNode = pHead;
while(currentNode.next != null
&& v.compareTo(currentNode.next.value) > 0){
currentNode = currentNode.next;
}
Node<E> newNode = new Node<E>(v);
newNode.next = currentNode.next;
currentNode.next = newNode;
}
}

void Output(){
if(pHead != null){
Node<E> currentNode = pHead;
while(currentNode != null){
System.out.print(currentNode.value + ", ");
currentNode = currentNode.next;
}
}
}
public static void main(String[] args) {
SortedLinkedList<Integer> list = new SortedLinkedList<Integer>();
list.newNode(3);
list.newNode(2);
list.newNode(6);
list.newNode(4);
list.newNode(1);
list.Output();
}
}


输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐