链表算法题理解和实现

一,链表的功能特征:

   1,集合数据存储,

   2,序列数据, 有顺序 

   3,不能随机读取 ,只能 按照固定顺序读取。   而数组具有通过索引随机读取的功能。

   4,具有递归嵌套结构,方便使用递归思想处理问题。

 

二, 链表的典型算法题型   

1,反转链表 
   思路: 双节点思路, 

         1,设置相邻节点,把链表分成2部分,一个已反转节点,一个待反转节点。 

         2,一起向前遍历,并做好反转处理。 

 1  public static Node reverseList(Node head){
 2         if(head == null || head.getNext() == null){  //null 或者 1个元素
 3             return head;
 4         }
 5         Node preNode = null;   // preNode 初始化null, 一起移动。设置变量。    链表的双指针,不是数组的i ,j.
 6         Node currentNode = head;
 7         while(currentNode != null){
 8             Node temp = currentNode.getNext();   //保存next节点
 9             currentNode.setNext(preNode);
10             preNode = currentNode;
11             currentNode = temp;    
12 
13         }
14         return preNode;
15     }

 

2,回文链表
     输入:head = [1,2,2,1]
     输出:true
思路:
  使用stack结构 ,把链表全部倒进去,然后弹出值和每个节点值比较。 如果每个值都相同,则是true。   另外,可以根据链表对称的特征,找到中心节点,可以链表节点比较过程优化。

 1  // 回文链表
 2     public static boolean parlindroomNode(Node head){
 3         // stack
 4         if(head == null || head.getNext() == null) return true;
 5         Stack<Integer> stack = new Stack<Integer>();  //优化比较一半
 6         int leng = 0;
 7         while(head != null){
 8             stack.push(head.getValue());
 9             head = head.getNext();
10             leng++;
11         }
12         leng <<= 1;
13         while(leng-- > 0){
14             if(head.getValue() != stack.pop()){ // half be compared
15                 return false;
16             }
17         }
18         return true;
19     }

3, 合并有序链表 

   思路 :采用递归思想

       1,如果head1 和head2的值大小,并选取合并后的第一个节点。假设时head1

  2, 把1过程的合并过程依次传入子结构中。继续递归比较。比如(head1.getNext() , head2)

       3,  递归终止条件是 null.

 1 // merge/combine/unify 2 link
 2     public static Node mergeNodes(Node head1, Node head2){
 3         //recurse thought
 4         if(head1 == null ) return head2;
 5         if(head2 == null ) return head1;
 6         Node merge = null;
 7         while(head1 != null && head2 != null){
 8             if(head1.getValue() <= head2.getValue()){
 9                 merge = head1;
10                 merge.setNext(mergeNodes(head1.getNext(), head2));  
11             }else{
12                 merge = head2;
13                 merge.setNext(mergeNodes(head2.getNext(), head1));
14             }
15 
16         }
17         return merge;
18 
19     }

 

掌握了常用技巧后,链表

 

posted @ 2022-06-15 12:20  gaussen126  阅读(28)  评论(0)    收藏  举报