题目:设计链表

设计链表                                                             

设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

在链表类中实现这些功能:

  • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
  • addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
  • addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
  • addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val  的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
  • deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
     

示例:

MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2);   //链表变为1-> 2-> 3
linkedList.get(1);            //返回2
linkedList.deleteAtIndex(1);  //现在链表是1-> 3
linkedList.get(1);            //返回3

提示:

  • 所有val值都在 [1, 1000] 之内。
  • 操作次数将在  [1, 1000] 之内。
  • 请不要使用内置的 LinkedList 库。
class MyLinkedList {

    /** Initialize your data structure here. */
    public MyLinkedList() {
             
    }
    
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    public int get(int index) {
                     
    }
    
    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    public void addAtHead(int val) {

    }
    
    /** Append a node of value val to the last element of the linked list. */
    public void addAtTail(int val) {

    }
    
    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    public void addAtIndex(int index, int val) {

    }
    
    /** Delete the index-th node in the linked list, if the index is valid. */
    public void deleteAtIndex(int index) {

    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */

以下为解题代码:

package 草稿;
     class ListNode {
	  int val;
	  ListNode next;
	  ListNode(int x) { val = x; }
	}

    public class MyLinkedList {
	       int size;
	       ListNode head;
	    /** Initialize your data structure here. */
	    public MyLinkedList() {
	            size = 0;
	            head = new ListNode(0);//这里的头指针相当于一个哨兵,并不会算在真正的队列里
	    }
	    
	    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
	    public int get(int index) {
	    	//这里注意是>=而不是>,这里可以参考数组,因为Index是从0开始的,所以最后一个索引总是比size小1
	          if(index>=size||index<0){
	        	  return -1;
	          }
		    	ListNode pointer = head;   //定义一个节点对象来充当指针的作用
		    	//往前移动index+1次,直至要查找的循环,+1是因为是从哨兵开始遍历,也可以i<=index
		          for(int i=0;i<index+1;i++){
		              pointer = pointer.next;
		          }
		          return pointer.val;
			
	    }
	    
	    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
	    public void addAtHead(int val) {
	         addAtIndex(0, val);
	         System.out.println("成功添加头节点");
	    }
	    
	    /** Append a node of value val to the last element of the linked list. */
	    public void addAtTail(int val) {
             addAtIndex(size, val);
             System.out.println("成功添加节点到尾部");  
	    }
	    
	    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
	    public void addAtIndex(int index, int val) {
               if (index>size) {
				return ;
			}
               if (index<0) {
				index = 0;
			}
               //准备开始插入,size加1
               size++;
              ListNode pointer = head;
              ListNode curr = new ListNode(val);//需要插入的节点
              if (size==0) {
				pointer.next = curr;//此段代码可以不加
			}
              else {
				for (int i = 0; i < index; i++) {
					pointer = pointer.next;
				}
				curr.next = pointer.next;
				pointer.next = curr;
			}
	    }
	    
	    /** Delete the index-th node in the linked list, if the index is valid. */
	    public void deleteAtIndex(int index) {
	    	//这里即索引不在范围内,即结束程序
	    	if (index>=size||index<0) {
	    		return ;
			}
	    	ListNode pointer = head;
	    	//准备删除,size减1
	    	size--;
	    	//这里遍历到删除节点的前一个节点
            for (int i = 0; i < index; i++) {
				pointer = pointer.next;
			}
            pointer.next =pointer.next.next;
            System.out.println("成功删除节点");
	    }
	}

	/**
	 * Your MyLinkedList object will be instantiated and called as such:
	 * MyLinkedList obj = new MyLinkedList();
	 * int param_1 = obj.get(index);
	 * obj.addAtHead(val);
	 * obj.addAtTail(val);
	 * obj.addAtIndex(index,val);
	 * obj.deleteAtIndex(index);
	 */




这里有几个地方需要注意,首先是链表中的哨兵节点,哨兵节点在树和链表中被广泛用作伪头、伪尾等,通常不保存任何数据。这里作为伪头存在,保证结构永不为空。

if(index>=size||index<0){
	        	  return -1;
	          }

然后就是上面代码中index>=size的问题,=也不可以是因为最大索引总是比链表长度小1,这里可以参考上图,这里最大索引是1,然而链表的长度是2。

最后是当size=0的时候的插入,实际的插入情况如下:

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值