Leetcode707设计链表
使用Java设计一个链表
package link_list;public class Design_Link {public static void main(String[] args) {Design_Link demo = new Design_Link();Design_Link.myLinkedList myLink = new Design_Link().new myLinkedList();myLink.addHead(0);myLink.addIndex(1,1);myLink.addTail(2);myLink.addTail(2);myLink.printVal();myLink.get(1);}class ListNode{int val;ListNode next;public ListNode() {}public ListNode(int val) {this.val=val;}public ListNode(int val,ListNode linkNode) {this.val=val;this.next = linkNode;}}class myLinkedList{//记录链表大小int size;//虚拟头结点ListNode head;public myLinkedList(){size = 0;head = new ListNode(0,null); }//获取第index个结点的数值,注意index是从0开始的,第0个结点就是头结点。public void get(int index) {if(index<0||index>=size) {System.out.print("格式错误");}ListNode cur = head;//包含虚拟结点,所以查找第index+1个结点for(int i =0;i<=index;i++) {cur = cur.next;}System.out.println(cur.val); }// 在第 index 个节点之前插入一个新节点,例如index为0,那么新插入的节点为链表的新头节点。// 如果 index 等于链表的长度,则说明是新插入的节点为链表的尾结点// 如果 index 大于链表的长度,则返回空public void addIndex(int index,int val) {if(index<0) {index = 0;}else if(index>size) {return;}size++;//找到要插入的结点前驱动ListNode pred = head;for(int i =0;i<index;i++) {pred = pred.next;}ListNode curAdd = new ListNode(val);curAdd.next = pred.next;pred.next= curAdd;}//插入最前面的节点,等价于在第0个元素添加public void addHead(int val) {addIndex(0,val);}//最后插入public void addTail(int val) {addIndex(size,val);}//删除第index个元素public void deleteIndex(int index) {if(index <0||index>=size) {return;}size--;ListNode pred = head;for(int i =0;i<index;i++) {pred = pred.next;}pred.next = pred.next.next;}public void printVal() {ListNode cur = head.next;if(cur!=null) {for(int i=0;i<size;i++) {System.out.print(cur.val+"\t");cur = cur.next;}}else {System.out.println("链表为空");}}}
}
LeetCode206反转链表
package link_list;
public class Revert_Link {public ListNode revertLink(ListNode head) {ListNode pre = new ListNode();ListNode cur = head.next;ListNode temp = new ListNode();while(temp!=null){temp = cur.next;cur.next = pre;pre = cur;cur=temp;}return pre;}
}