Java面试宝典——如何实现单链表的增删操作

论坛 期权论坛 脚本     
匿名技术用户   2020-12-23 15:55   213   0

链表增加结点(把新增加的结点放到链表尾部)

删除链表中的结点

计算链表的长度

通过插入排序,实现对链表的排序


package linkedlist;
/**
 * @author wyl
 * @time 2018年7月4日下午4:01:54
 */
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;  
 }
 
 /**
  * @param index :删除第index个结点
  * @return
  */
 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;  //preNode指向头结点
  Node curNode=preNode.next;  //curNode指向头结点的下一个结点,即当前结点
  while(curNode!=null){ //当前结点非空
   if (i==index) {
    preNode.next=curNode.next;
    return true;
   }
   preNode=curNode;
   curNode=curNode.next;
   i++;
  }
  return true;
 }
 
 /**
  * @return :返回结点的长度
  */
 private int length() {
  // TODO Auto-generated method stub
  int length=0;
  Node tmp=head;
  while(tmp!=null){
   length++;
   tmp=tmp.next;
  }
  return length;
 }

 /** 
  * 对链表进行排序 
  * @return  排序后的头结点
  */
 public Node orderList(){ //冒泡排序~~~~~~~
  Node nextNode=null;
  int tmp=0;
  Node curNode=head;
  while(curNode.next!=null){
   nextNode=curNode.next;
   while(nextNode!=null){
    if (curNode.data>nextNode.data) {//exchanhe
     tmp=curNode.data;
     curNode.data=nextNode.data;
     nextNode.data=tmp;
    }
    nextNode=nextNode.next;
   }
   curNode=curNode.next;
  }
  return head;
 }
 
 /**
  * 打印链表结点
  */
 public void printList(){
  Node tmp=head;
  while(tmp!=null){
   System.out.println(tmp.data);
   tmp=tmp.next;
  }
 }
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  MyLinkedList list=new MyLinkedList();
  list.addNode(1);
  list.addNode(3);
  list.addNode(2);
  System.out.println("链表长度:"+list.length());
  list.printList();
  list.orderList();
  list.printList();
 }

}
package linkedlist;
/**
 * @author wyl
 * @time 2018年7月4日下午4:04:28
 */
public class Node {
 Node next=null;
 int data;
 public Node(int data) {
  this.data=data;
 }
}


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP