Java实现链表的增.删与逆置
链表是数据结构中很重要的一项,它的优点就是便于增删改,所以我们有必要理解与实现链表的基本功能
class Node{
public int value;
public Node next;
public Node(int value) {
this.value=value;
this.next=null;
}
}
//输出
public class LinkedList {
public static void displayLinkedList(Node head) {
//遍历一个链表
for(Node cur=head;cur!=null;cur=cur.next) {
System.out.printf("%d->", cur.value);
}
System.out.println("null");
}
//创建初始链表数据
public static Node creatLinkedList() {
Node n1=new Node(1); //首结点(头结点)
Node n2=new Node(2);
Node n3=new Node(3);
Node n4=new Node(4);
Node n5=new Node(5);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
n5.next=null;
return n1;
}
//头插
public static Node pushFront(Node head,int value) {
//1.申请新结点
Node newNode=new Node(value);
//2.更新newNode的next
newNode.next=head;
//3.更新head
//head=newNode;
return newNode;
}
//找到原来最后一个结点
public static Node getLast(Node head) {
Node cur=head;
for(;cur.next!=null;cur=cur.next) {
}
return cur;
}
//尾插
public static Node pushBack(Node head,int value) {
//对空链表尾插
if(head==null) {
return pushFront(head, value);
}//对非空链表尾插
else {
//1.申请新结点,并且让next=null
Node newNode=new Node(value);
//2.找到当前的最后一个结点
Node lastNode=getLast(head);
//3.让当前的最后一个结点的next=newNode
lastNode.next=newNode;
return head;
}
}
//删除值和给出的一样的结点
public static Node removeElements(Node head,int value) {
Node newList=null;
Node lastNode=null; //用来记录newList链表的最后一个结点
Node cur=head;
while(cur!=null) {
Node nextNode=cur.next; //下面的代码会变更cur.next
if(cur.value!=value) {
//把cur尾插到newList链表
if(newList==null) { //第一次尾插是,newList是空链表
cur.next=newList;
newList=cur;
}else { //以后尾插时,newList不是空链表
lastNode.next=cur;
}
lastNode=cur; //负责更新last,保证lastnode始终是最后一个结点
}
cur=nextNode;
}
if(lastNode!=null) {
lastNode.next=null;
}
return newList;
}
//头删
public static Node popFront(Node head) {
if(head==null) {
System.out.println("参数不合法,无法删除空链表的结点");
return null;
}
return head.next;
}
private static Node getlastLast(Node head) {
Node cur=head;
while(cur.next.next!=null) {
cur=cur.next;
}
return cur;
}
//尾删
public static Node popBack(Node head) {
if(head==null) {
System.out.println("参数不合法,无法删除空链表的结点");
return null;
}
if(head.next==null) {
//链表中只有一个结点
//可以视作头删处理
return null;
}else {
//1.找倒数第二个结点
Node lastLast=getlastLast(head);
//2.让倒数第二个结点的next=null
lastLast.next=null;
//3.释放原最后一个结点(GC负责)
}
return head;
}
//逆置
public static Node reverseList(Node head) {
//依次遍历原链表每个结点,头插到一个新的链表
Node newList=null;
Node cur=head;
while(cur!=null) {
//cur.next会变化,提前保存它的值
Node next=cur.next;
//头插
cur.next=newList;
newList=cur;
//让cur往后遍历
cur=next;
}
return newList;
}
public static void main(String[] args) {
Node head= null;
head=pushBack(head, 1);
head=pushBack(head, 2);
head=pushBack(head, 3);
displayLinkedList(head);
head=pushFront(head, 30);
head=pushFront(head, 20);
head=pushFront(head, 10);
head=pushFront(head, 1);
displayLinkedList(head);
head=popBack(head);
displayLinkedList(head);
reverseList(head);
displayLinkedList(head);
//removeElements(head, 1);
//displayLinkedList(head);
}
}