数据结构与算法学习之链表的增加、删除

package com.java;

class Node {
	Node next=null;
	int data;
	public Node(int data) {
		// TODO Auto-generated constructor stub
	this.data=data;
	}	
}


public class ImpAddDel {

	Node head = null;//链表头的引用
	/**
	 * 向链表中插入数据
	 * @param d插入数据的内容
	 */
	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;
			
		}
		//add node to end 
		tmp.next=newNode;
	}
	/**
	 * 删除节点
	 * @param index要删除的节点下标
	 * @return 成功返回true 失败返回false;
	 */
	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;
		Node curNode = preNode.next;
		while (curNode!=null)
		{
			if (i==index) {
				preNode.next= curNode.next;
				return true;
			}
			preNode=curNode;
			curNode=curNode.next;
			i++;
		}
		return true;
	}
	
	/**
	 * 
	 * @return 返回节点的长度
	 */
	public int length() {
		// TODO Auto-generated method stub
		int length =1 ;
		Node tmp =head;
		while(tmp.next!=null){
			length++;
			tmp= tmp.next;
		}
		return length;
	}
	
	/**
	 * 链表排序
	 * @return返回链表头的引用
	 */
	public Node orderList(){
		Node nextNode = null ;
		int temp=0;
		Node curNode=head;
		while(curNode.next!=null){
			nextNode=curNode.next;
			while(nextNode!=null){
				if (curNode.data>nextNode.data) {
					temp=curNode.data;
					curNode.data=nextNode.data;
					nextNode.data=temp;
					
				}
				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;
		}
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ImpAddDel list = new ImpAddDel();
		list.addNode(5);
		list.addNode(3);
		list.addNode(1);
		list.addNode(3);
		System.out.println("listLen = "+ list.length());
		System.out.println("before order:");
		list.printList();
		list.orderList();
		System.out.println("after order:");
		list.printList();
		list.deleteNode(2);
		list.printList();
		
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值