题目:
Reverse a singly linked list.
分析:
题目考察链表的反转,在这里主要是next指针的调整,利用指向前一个结点的指针before,指向后一个结点的指针followee,从而实现链表的反转。
代码:
package Code;
public class LinkedList {
/**
* 链表结点类
* @author Don
*
*/
public static class ListNode{
int val;
ListNode next;
ListNode(int x){val=x;}
}
/**
* 反转链表方法
* @param head
* @return
*/
public static ListNode reverseList(ListNode head){
ListNode before=null;
while(head!=null){
ListNode followee=head.next;
head.next=before;
before=head;
head=followee;
}
return before;
}
/**
* 构建单链表
* @param node
* @param val
*/
public static ListNode buildLinkedList(int[] a){
ListNode before=null;
for(int i=0;i<a.length;i++){
ListNode node=new ListNode(a[i]);
node.next=before;
before=node;
}
return before;
}
/**
* 打印单链表
* @param node
*/
public static void show(ListNode head){
while(head!=null){
System.out.print(head.val+".");
head=head.next;
}
}
public static void main(String[] args){
int[] a={1,2,3,4,5};
ListNode head=buildLinkedList(a);
show(head);
System.out.println();
ListNode temp=reverseList(head);
show(temp);
}
}