单链表的增、删、排序
package com.sf.linkedlist;
/**
* Created by ... on 2016/11/30.
*/
class Node{
Node next=null;
int val;
public Node(int val){
this.val=val;
}
}
public class SingleLinkedList {
static Node head=null;
public static void main(String args[]){
head=new Node(9);
Node next1=new Node(3);
Node next2=new Node(5);
Node next3=new Node(3);
Node next4=new Node(10);
head.next=next1;
next1.next=next2;
next2.next=next3;
next3.next=next4;
showList(head);
//insert(next4);//插入最后一个位置
//insertSorted(next4);//插入合适的位置,使得原链表依然是有序的。
/*if(delete(2)) //删除元素
showList(head);
else{
System.out.print("failure");
}*/
head=sort();
showList(head);
}
//1.单链表的插入操作
/**
* 1.1 单链表的“增”——插入操作
* 插入的节点为node,插到链表最后
* */
public static void insert(Node node){
if(head==null){
head=node;
return;
}
Node tmp=head;
while(tmp.next!=null){
tmp=tmp.next;
}//while循环是用来找到最后一个节点
tmp.next=node;
}
/**
* 1.2 单链表的“增”——插入操作
* 原链表是有序的(升序),请在插入之后仍保持链表的有序性。
* 插入的节点为node,重点找到插入的位置。
* */
public static void insertSorted(Node node){
if(head==null) {
head = node;
return;
}
Node tmp=head;
if(tmp.val>=node.val) {//插入节点的值最小
node.next=tmp.next;
tmp.next=node;
return;
}
while(tmp.next!=null){//插入节点的值在中间位置
if(tmp.val<=node.val && tmp.next.val>=node.val){
node.next=tmp.next;
tmp.next=node;
return;
}
tmp=tmp.next;
}
tmp.next=node;//插入节点在最后位置
}
//2 删除链表中的某个节点
/**
* 2.1 单链表的“删”——删除操作
* 删除第index个节点
* 重要的是找到第index个节点。将它的前一个节点指向它的后一个节点。
* 注意要在程序中“保留”index节点的前一个节点.preNode/currNode.
* currNode就是要删除的目标元素。
* */
public static boolean delete(int index){
if(index<1 || index>length()){
return false;//删除不存在的节点,返回false;
}
if(index==1){//删除第一个节点
head=head.next;
return true;
}
int i=2;
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;
}
//3 对链表排序,返回排好序的头元素
/**
* 3.1 对链表排序,升序排序
* 其实思路挺简单的:
* 如果是升序,先把第一个位置要放的最小值找到,然后第二个位置。。。。第n-1个位置。
* 前面n-1个位置上的元素确定了,那么第n个位置上的元素也就确定了。
*
*
* */
public static Node sort(){
if(head==null)
return head;
Node tmp=head;
while(tmp.next!=null){//循环到倒数第二个位置。
Node nextNode=tmp.next;
while(nextNode!=null){ //找到目标值(本轮最小值),放在tmp位置上。
if(tmp.val>nextNode.val){
int temp=tmp.val;
tmp.val=nextNode.val;
nextNode.val=temp;
}
nextNode=nextNode.next;
}
tmp=tmp.next;
}
return head;
}
/**
* 打印链表
* */
public static void showList(Node head){
if(head==null)
return;
Node tmp=head;
while(tmp!=null)
{
if(tmp.next!=null) {
System.out.print(tmp.val+"->");
tmp = tmp.next;
}else{
System.out.print(tmp.val);
tmp = tmp.next;
}
}
System.out.println();
}
/**
* 获取链表的长度
* */
public static int length(){
int length=0;
Node tmp=head;
while(tmp!=null){
length++;
tmp=tmp.next;
}
return length;
}
}