单、双向链表操作

昨天的笔试题有一个双向链表的操作,我本来很有自信的,怎么老是感觉做错了?  woc

 

单链表的增加和删除

/**
 * @author JZWen
 * @date  2019年3月8日
 */
package getoffer;

/**
 * @author JZWen
 *
 */
public class SimpleLinked {

	
	public static int delete(LinkNode linkNode , int i) {
		LinkNode curr = linkNode;
		if(curr == null) {
			return 0;
		}
		int len = 0;
		while(curr != null) {
			len ++;
			if(len == i) {
				
				if(curr.next == null) {
					return 1;
				}
				//重点,删除
				curr.next = curr.next.next;
				return 1;
			}
			curr = curr.next;
		}
		//长度太长了
		return 0;
	}
	
	public static int insert(LinkNode linkNode , int i , int value) {
		
		LinkNode curr = linkNode;
		if(curr == null) {
			return 0;
		}
		int len = 0;
		while(curr != null) {
			len ++;
			if(len == i) {
				//插入操作
				LinkNode newNode = new LinkNode(value);
				newNode.next = curr.next;
				curr.next = newNode;
				return 1;
			}
			curr = curr.next;
		}
		//长度太长了
		return 0;
	}
	
	
	
	
	public static void print(LinkNode linkNode) {
		LinkNode curr = linkNode;
		while(curr != null) {
			System.out.println(curr.value);
			curr = curr.next;
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkNode linkNode = new LinkNode(1);
		LinkNode linkNode1 = new LinkNode(2);
		LinkNode linkNode2 = new LinkNode(4);
		linkNode.next = linkNode1;
		linkNode1.next = linkNode2;
		insert(linkNode , 2, 3);
		delete(linkNode, 2);
		print(linkNode);
	}	

}

class LinkNode{
	
	LinkNode next;

	int value;
	
	public LinkNode() {}
	
	public LinkNode(int value) {
		this.value = value;
	}
	
}

 

单链表翻转  还有头插法,还有就地解决法

//反转链表
	public LinkNode fanzhuan(LinkNode linkNode) {
		//最简单的方法就是,有一个堆栈存储链表节点,以最先出栈的为头结点。
		Stack<LinkNode> stack = new Stack<>();
		while(linkNode != null) {
			stack.push(linkNode);
			linkNode = linkNode.next;
		}
		LinkNode head = new LinkNode();
		if(!stack.isEmpty()) {
			head = stack.pop();
		}
		LinkNode node = head;
		while(!stack.isEmpty()) {
			node.next = stack.pop();
		}
		return head;
	}

 

单链表排序 , 使用的是类似于现在排序的算法。

*******************************************************刚看一下手机,作业帮约我下周面试。*************woc有点慌啊

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值