当前位置:   article > 正文

【数据结构】实现对链表的头插和尾插_链表插入允许插入表头和表尾嘛

链表插入允许插入表头和表尾嘛

 对于一个链表,要对其进行插入,可以分成头插,尾插和指定位置插入,下面代码中,我只涉及到了头插和尾插。
 

头插

首先定义一个node,如果head的值为null,直接返回node;如果head的值不为null,将node.next指向head,再把node作为头结点,再返回head。说是两种情况,其实用后者的代码就能全部包含。

假设这是一个不为空的链表(图1),head指向的是1,此时我们需要头插一个新的节点 3 ,插入后如图2,头插结束

                                                                                                    

 

尾插

如果链表是空链表,直接返回null或者说head,此时链表都为null了,那head肯定也是null。

如果不为空,定义一个新的节点cur让其指向head,定义cur的目的是能够找到链表的最后一个节点的位置。

当cur.next == null 时,此时cur处于最后一个节点的位置,如图3。将cur.next指向node,然后再让node.next == null,再让cur指向最后一个节点的位置,尾插就完成了,如图4。

                                                                                  

  1. public class LinkedList {
  2. public static void main(String[] args) {
  3. Node head = null;
  4. head = pushFront(head,0);
  5. }
  6. //头插(返回的是新的节点)
  7. private static Node pushFront(Node head,int val){
  8. Node node = new Node(val);
  9. node.next = head;
  10. head = node;
  11. return head;
  12. }
  13. //尾插
  14. private static Node pushBack(Node head,int val){
  15. Node node = new Node(val);
  16. if (head == null){
  17. return node;
  18. }else {
  19. Node cur = head;
  20. while (cur.next != null) {
  21. cur = cur.next;
  22. }
  23. cur.next = node;
  24. node.next = null;
  25. cur = node;
  26. return head;
  27. }
  28. }
  29. //打印
  30. public static void print(Node head){
  31. Node cur = head;
  32. while(cur != null){
  33. System.out.print(cur+" ");
  34. cur = cur.next;
  35. }
  36. }
  37. }
  38. class Node{
  39. int val;
  40. Node next;
  41. public Node(int val) {
  42. this.val = val;
  43. }
  44. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/444138
推荐阅读
相关标签
  

闽ICP备14008679号