1.链表的基本概念:
概念:链表是一种物理存储结构上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的 。(也就说逻辑上有前后关系,物理上不一定有)。
2.链表的基本操作:
1) 头插
(1)如果没有结点先建立一个结点
Node node=new Node(val);//val是插入的数值
(2)让原来的第一个结点成为新结点的下一个结点
node.next=head;
(3)更新最新的一个结点为头结点
head=node;
代码如下:
Node pushFront(Node head,int val)
{
Node node=new Node(val);
node.next=head;
return node;
}
2)尾插
如果链表非空:
(1)如果没有结点,新建一个结点
Node node=new Node(val);//val是插入的数值
(2)把新结点的next置为空
(3)找到链表的最后一个结点
Node last=head;
while(last.next!=null)
{
last=last.next;
}
(4)把新结点插到最后一个结点后面
last.next=node;
如果链表为空:
直接返回当前结点
代码如下:
Node pushBack(Node head,int val)
{
Node node=new Node(val);
if(head==null)
{
return node;
}
else
{
Node last=head;
while(last.next!=null)
{
last=last.next;
}
last.next=node;
return head;
}
}
3)头删
(1)首先判断链表是否为空,下面只讨论链表不为空的情况
(2)把head的next给head
代码如下:
public Node popFront(Node head)
{
if(head==null)
{
System.out.println("链表为空,无法删除");
return null;
}
head=head.next;
return head;
}
(4)尾删
1)首先判断链表是否为空,下面只讨论链表不为空的情况
2) 在分两种情况
- 链表只有一个结点时(即head.next为空时),直接返回空结点。
- 链表多于一个结点时:
- 找到倒数第二个结点
Node second=head;
while(second.next.next!=null)
{
second=second.next;
}
2.把倒数第二个结点的next置为空
second.next=null;
代码如下:
public Node popBack(Node head)
{
if(head==null)
{
System.out.println("链表为空,无法删除");
return null;
}
if(head.next==null)
{
return null;
}
else
{
Node second=head;
while(second.next.next!=null)
{
second=second.next;
}
second.next=null;
return head;
}
}
这里有一个打印链表的函数:
Node cur=head;
while(cur!=null)
{
System.out.print(cur.val );
cur=cur.next;
}
整体代码如下:
class Node {
int val;
Node next=null;
public Node(int val)
{
this.val=val;
}
public Node()
{
}
Node pushFront(Node head,int val)
{
Node node=new Node(val);
node.next=head;
return node;
}
Node pushBack(Node head,int val)
{
Node node=new Node(val);
if(head==null)
{
return node;
}
else
{
Node last=head;
while(last.next!=null)
{
last=last.next;
}
last.next=node;
return head;
}
}
public Node popFront(Node head)
{
if(head==null)
{
System.out.println("链表为空,无法删除");
return null;
}
head=head.next;
return head;
}
public Node popBack(Node head)
{
if(head==null)
{
System.out.println("链表为空,无法删除");
return null;
}
if(head.next==null)
{
return null;
}
else
{
Node second=head;
while(second.next.next!=null)
{
second=second.next;
}
second.next=null;
return head;
}
}
public void linkedPrint(Node head)
{
Node cur=head;
while(cur!=null)
{
System.out.print(cur.val );
cur=cur.next;
}
}
public static void main(String[] args)
{
Node head=null;
Node node= new Node();
head=node.pushFront(head,2);
head=node.pushBack(head, 2);
head=node.pushFront(head, 3); //3 2 2
node.linkedPrint(head);
System.out.println();
head=node.popFront(head); //2 2
head=node.popBack(head); //2
node.linkedPrint(head);
}
}
运行截图如下: