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

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

删除链表中的结点

计算链表的长度

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


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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Baymax_wyl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值