链表操作

package cn.day18;

import java.util.ArrayList;

import com.sun.org.apache.regexp.internal.recompile;

public class LinkData {
	
	public ListNode  addLinkNade(ListNode headNode ,ListNode insertNode){
		
		if(headNode == null){
			headNode = insertNode;
			return headNode;
		}else{
			ListNode pNode = headNode;
			while(pNode.getNextNode() != null){
				pNode = pNode.getNextNode();
			}
			ListNode currentNode = pNode.getNextNode();
			insertNode.setNextNode(currentNode);
			pNode.setNextNode(insertNode);;
			return headNode;
		}
	}
	/**
	 * 指定位置删除链表
	 * @param headNode
	 * @return
	 */
	public ListNode deleteListNodeByPosition(ListNode headNode,int position){
		if(headNode == null){
			return headNode;
		}
		if(position == 1){//删除表头
			ListNode currentNode = headNode.getNextNode();
			headNode = null;
			return currentNode;
		}else{//删除中间或未尾
			ListNode pNode = headNode;
			int count = 1;
			while (count < position -1){
				count++;
				pNode = headNode.getNextNode();
			}
			ListNode currentNode = pNode.getNextNode();
			pNode.setNextNode(currentNode.getNextNode());
			currentNode = null;
		}
		
		
		return headNode;
	}
	/**
	 * 打印链表
	 * @param headNode
	 */
	public void printListNode(ListNode headNode){
		if(headNode == null){
			System.out.println("链表为空!!!");
			return ;
		}
		while(headNode.getNextNode() != null){
			
			System.out.println();
			
		}
	}
	/**
	 * 获取链表大小
	 * @param headNode
	 * @return
	 */
	public int getSize(ListNode headNode){
		int count = 0;
		if (headNode != null){
			count =1;
		}
		ListNode pNode = headNode;
		while(pNode.getNextNode() != null){
			pNode = pNode.getNextNode();
			count++;
		}
		
		return count;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ListNode  headNode =  null;
		LinkData  link = new LinkData();
		ListNode node1 = new ListNode(10);
		headNode = link.addLinkNade(headNode,node1);
		
		ListNode node2 = new ListNode(20);
		headNode = link.addLinkNade(headNode,node2);
		
		
		ListNode node3 = new ListNode(30);
		headNode = link.addLinkNade(headNode,node3); 
		
		
		link.deleteListNodeByPosition(headNode, 2);
		
		System.out.println(headNode);
		System.out.println("大小==="+link.getSize(headNode));
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值