4.4 链表的遍历、查询和修改

1.获取链表index位置的元素

 1  public E get(int index){   //创建方法get(index),获取索引为index的元素
 2 
 3         if(index < 0 || index >= size)
 4             throw new IllegalArgumentException("Get failed. Illegal index.");
 5 
 6         Node cur = dummyHead.next;  //cur:索引为0的元素
 7         for(int i = 0 ; i < index ; i ++)   //进行变量
 8             cur = cur.next;
 9         return cur.e;
10     }
11 
12     // 获得链表的第一个元素
13     public E getFirst(){
14         return get(0);
15     }
16 
17     // 获得链表的最后一个元素
18     public E getLast(){
19         return get(size - 1);
20     }

2 修改链表index位置的元素(更新)

 1  // 修改链表的第index(0-based)个位置的元素为e
 2     // 在链表中不是一个常用的操作,练习用:)
 3     public void set(int index, E e){
 4         if(index < 0 || index >= size)
 5             throw new IllegalArgumentException("Set failed. Illegal index.");
 6 
 7         Node cur = dummyHead.next;
 8         for(int i = 0 ; i < index ; i ++)   //进行遍历
 9             cur = cur.next;
10         cur.e = e;
11     }

3 查找

 1  // 查找链表中是否有元素e
 2     public boolean contains(E e){
 3         Node cur = dummyHead.next;
 4         while(cur != null){
 5             if(cur.e.equals(e))
 6                 return true;
 7             cur = cur.next;
 8         }
 9         return false;
10     }

4.打印输出

 1 public String toString(){
 2         StringBuilder res = new StringBuilder();
 3 
 4 //        Node cur = dummyHead.next;
 5 //        while(cur != null){
 6 //            res.append(cur + "->");
 7 //            cur = cur.next;
 8 //        }
 9         for(Node cur = dummyHead.next ; cur != null ; cur = cur.next) //等价于上面的while循环
10             res.append(cur + "->");
11         res.append("NULL");
12 
13         return res.toString();
14     }

猜你喜欢

转载自www.cnblogs.com/make-big-money/p/10322249.html
4.4