ListNode是单链表节点的数据结构,实现见如下代码:package List; /** * Created by Administrator on 2015/10/10. */public class ListNode { //节点的值 private char data; //节点的后续节点 private ListNode next; public ListNode(char data, ListNode next) { this.data = data; this.next = next; } public ListNode(ListNode next){ this.next=next; } public char getData() { return data; } public void setData(char data) { this.data = data; } public ListNode getNext() { return next; } public void setNext(ListNode next) { this.next = next; }}那么对于链表的反转操作及其测试用例如下:
package List; /** * Created by Administrator on 2015/10/10. */public class NodeUtil { public static void printList(ListNode head){ if(head.getNext()==null){ System.out.println("此链表为空!"); }else{ ListNode p=head.getNext(); while (p.getNext()!=null){ System.out.print(p.getData()+"->"); p=p.getNext(); } System.out.print(p.getData()); } } //反转链表 public static ListNode reverseLinkedList(ListNode head){ ListNode p=head.getNext(); ListNode q=p.getNext(); p.setNext(null); while (q.getNext()!=null){ ListNode nextQ=q.getNext(); q.setNext(p); p=q; q=nextQ; } q.setNext(p); ListNode root=new ListNode(q); return root; } //测试 public static void main(String[] args){ ListNode D=new ListNode(‘D‘,null); ListNode C=new ListNode(‘C‘,D); ListNode B=new ListNode(‘B‘,C); ListNode A=new ListNode(‘A‘,B); ListNode head=new ListNode(A); System.out.println("反转链表之前"); printList(head); System.out.println(); System.out.println("反转链表之后"); ListNode root=reverseLinkedList(head); printList(root); }}
时间: 2024-10-21 17:32:33