class Node{
public int value;
public Node next=null;
public Node(int value) {
this.value=value;
}
}
public class LinkedList {
public static void display(Node head) {
for(Node cur=head;cur!=null;cur=cur.next) {
System.out.printf("(%d)->",cur.value);
}
System.out.printf("null");
System.out.printf("%n");
}
public static Node pushFront(Node head,int value) {
Node newnode=new Node(value);
newnode.next=head;
return newnode;
}
public static Node pushBack(Node head,int value) {
if(head==null) {
return pushFront(head,value);
}else {
Node newnode=new Node(value);
Node last=getlast(head);
last.next=newnode;
}
return head;
}
public static Node getlast(Node head) {
Node cur=head;
while(cur.next!=null) {
cur=cur.next;
}
return cur;
}
public static Node reverseList(Node head) {
Node newList=null;
Node cur=head;
while(cur!=null) {
Node next=cur.next;
cur.next=newList;
newList=cur;
cur=next;
}
return newList;
}
public static Node removeElements(Node head,int value) {
Node newlist=null;
Node cur=head;
while(cur!=null) {
Node next=cur.next;
Node last=null;
if(cur.value!=value) {
if(newlist==null) {
cur.next=newlist;
newlist=cur ;
}else {
last=newlist;
while(last.next!=null) {
last=last.next;
}
last.next=cur;
cur.next=null;
}
}
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);
display(head);
head=pushFront(head,10);
head=pushFront(head,20);
head=pushFront(head,30);
display(head);
head=reverseList(head);
display(head);
head=pushBack(head,1);
display(head);
head=removeElements(head,1);
display(head);
}
}
[Java]链表的打印,反转与删除
最新推荐文章于 2019-08-05 21:11:29 发布