赞
踩
头插
首先定义一个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。
- public class LinkedList {
- public static void main(String[] args) {
- Node head = null;
- head = pushFront(head,0);
- }
- //头插(返回的是新的节点)
- private static Node pushFront(Node head,int val){
- Node node = new Node(val);
- node.next = head;
- head = node;
- return head;
- }
- //尾插
- private static Node pushBack(Node head,int val){
- Node node = new Node(val);
- if (head == null){
- return node;
- }else {
- Node cur = head;
- while (cur.next != null) {
- cur = cur.next;
- }
- cur.next = node;
- node.next = null;
- cur = node;
- return head;
- }
- }
- //打印
- public static void print(Node head){
- Node cur = head;
- while(cur != null){
- System.out.print(cur+" ");
- cur = cur.next;
- }
- }
- }
- class Node{
- int val;
- Node next;
- public Node(int val) {
- this.val = val;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。