Reverse a linked list.

网友投稿 578 2022-10-12

Reverse a linked list.

Reverse a linked list.

public class OneLinkNode { public int data; public OneLinkNode next; public OneLinkNode(int k) { data = k; next = null; } public OneLinkNode() { this(0); } public static void main(String args[]) { int n = 7; OneLinkNode head = create(n); insert(head, 3, 30); OneLinkNode p = head; for (int i = 0; i < n + 1; i++) { System.out.print(p.data + " "); p = p.next; } System.out.println(); delete(head, 4); p = head; for (int i = 0; i < n; i++) { System.out.print(p.data + " "); p = p.next; } head=reverse3(head); System.out.println(); p = head; for (int i = 0; i < n; i++) { System.out.print(p.data + " "); p = p.next; } System.out.println(); OneLinkNode a = new OneLinkNode(); a.data=1; OneLinkNode b = new OneLinkNode(); b.data=2; revert(a, b); System.out.print(a.data+" "+b.data); } public static OneLinkNode reverse(OneLinkNode head,int n){ OneLinkNode[] p=new OneLinkNode[n]; p[0]=head; for(int i=0;i

public static OneLinkNode reverse2(OneLinkNode head,int n){ OneLinkNode p1=head; OneLinkNode p2=head.next; OneLinkNode p3=head.next; OneLinkNode temp; p1.next=null; for(int i=0;i

public static void revert(OneLinkNode a,OneLinkNode b){ OneLinkNode temp; temp=a; a=b; b=temp; }

public static OneLinkNode create(int n) { // 建立单链表 OneLinkNode rear, q, head = null; if (n > 0) { int k = (int) (Math.random() * 100); head = new OneLinkNode(k); rear = head; for (int i = 0; i < n - 1; i++) { k = (int) (Math.random() * 100); q = new OneLinkNode(k); rear.next = q; rear = q; } } return head; }

public static boolean insert(OneLinkNode head, int n, int data) {// 在第n个后插入data if (head == null) return false; OneLinkNode p = head; for (int i = 0; i < n - 1; i++) { p = p.next; } OneLinkNode newNode = new OneLinkNode(); newNode.data = data; newNode.next = p.next; p.next = newNode; return true; } public static boolean delete(OneLinkNode head, int n) {// 把第n个删除 if (head == null) return false; OneLinkNode p1 = head; for (int i = 0; i < n - 2; i++) { p1 = p1.next; } p1.next = p1.next.next; return true; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:用于响应式编程的一个Swift框架(swift的逻辑结构)
下一篇:Insert in a sorted list
相关文章

 发表评论

暂时没有评论,来抢沙发吧~