昨天的笔试题有一个双向链表的操作,我本来很有自信的,怎么老是感觉做错了? 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 stubLinkNode 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 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有点慌啊










