import java.util.*; public class Lianbiao { public static void main(String args[]){ Scanner in=new Scanner(System.in); ListNode head=new ListNode(0); head.next=null; ListNode head2=head; int n=in.nextInt(); //插入链表尾部 for(int i=0;i<n;i++){ int value=in.nextInt(); ListNode temp=new ListNode(value); temp.next=null; head2.next=temp; head2=head2.next; } print(head); DeleteNode(head,2); print(head); InsertNode(head,2,8); print(head); ReverseNode(head); print(head); System.out.println(getNode(head,3)); } //删除一个节点 public static void DeleteNode(ListNode head,int pos){ ListNode head2=head; for(int i=0;i<pos-1;i++){ head=head.next; } head.next=head.next.next; head=head2; } //插入一个节点 public static void InsertNode(ListNode head,int pos,int value){ ListNode head2=head; for(int i=0;i<pos-1;i++){ head=head.next; } ListNode newNode=new ListNode(value); newNode.next=head.next; head.next=newNode; head=head2; } //链表反转 public static void ReverseNode(ListNode head){ ListNode head2=head.next; List list=new ArrayList<Integer>(); while(head2!=null){ list.add(head2.value); head2=head2.next; } head2=head; for(int i=list.size()-1;i>=0;i--){ ListNode temp=new ListNode((int)list.get(i)); temp.next=null; head2.next=temp; head2=head2.next; } } //查询一个节点 public static int getNode(ListNode head,int pos){ ListNode head2=head; for(int i=0;i<pos;i++){ head2=head2.next; } return head2.value; } //打印 public static void print(ListNode head){ ListNode head0=head; head0=head0.next; while(head0!=null){ System.out.print(head0.value+" "); head0=head0.next; } System.out.println(); } } class ListNode{ int value; ListNode(int value){ this.value=value; } ListNode next; }
链表的基本操作-增删查逆序
最新推荐文章于 2023-04-03 16:46:56 发布