基于链表的插入排序

//链表的插入排序

import java.io.*;

class IntList extends List
{
  int element;
  IntList next;

  public static final IntList nil = null;
  public static int first(IntList L)
  {
    return L.element;
  }
  public static IntList next(IntList L)
  {
    return L.next;
  }
  public static IntList cons(int newElement,IntList oldList) //创建值为newElement的新节点,并接在原链表头
  {
    IntList newL = new IntList();
    newL.element = newElement;
    newL.next = oldList;
    return newL;
  }
}


public class insert1
{
  public static IntList insert1(int newElement, IntList oldList)
  {
    IntList newList = new IntList();
    newList.element = newElement;
    newList.next = null;
    IntList p, q;
    p = oldList;
    q = p;
    if (newList.element <= oldList.element) {
      newList.next = oldList;
      return newList;
    }
    else {
      p = p.next;
      if (p == null) {q.next = newList; return q;}
      while (p != null) {
        if (newList.element <= p.element) {
          newList.next = p;
          q.next = newList;
          return oldList;
        }
        else {
          q = p;
          p = p.next;
        }
        if(p == null)
        {
          q.next = newList;
          return oldList;
        }
      }
      return oldList;
    }
  }

  public static void main(String[] args) throws Exception
  {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in,
        "GBK"));
    IntList initlist = new IntList();
    initlist.element = 5;
    initlist.next = null;
    IntList p = initlist;
    while (true) {
      System.out.println("请输入新插入的节点的element值:");
      String s = br.readLine();
      int b = Integer.parseInt(s);
      if (b == -1)  break;
      p = insert1(b, p);
    }
    while (p != null) {
      System.out.println(p.element);
      p = p.next;
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值