面试题24:反转链表
题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
需要注意的:
输入空结点
链表只有一个节点
public class Q24 {
public static void main(String[] args) {
ListNode head = getList();
printLink(head);
head = reverse(head);
if(head!=null) {
System.out.println("-----------");
printLink(head);
}else {
System.out.println("head is null!");
}
}
// 反转链表
public static ListNode reverse(ListNode head) {
// 空链表或只含一个节点 返回head
if(head==null||head.next==null) {
return head;
}
ListNode preNode = head;
ListNode locNode = head.next;
ListNode saveNode = locNode.next;
head.next = null;
while(saveNode!=null) {
locNode.next = preNode;
preNode = locNode;
locNode = saveNode;
saveNode = saveNode.next;
}
locNode.next = preNode;
return locNode;
}
// 创建链表
public static ListNode getList() {
System.out.printf("input:");
Scanner sc = new Scanner(System.in);
ListNode head = new ListNode(0);
ListNode node = head;
while(sc.hasNextInt()) {
ListNode temp = new ListNode(sc.nextInt());
node.next = temp;
node = temp;
}
return head.next;
}
// 打印链表
public static void printLink(ListNode head) {
System.out.print("your list:");
while(head!=null) {
System.out.printf("%d ", head.val);
head = head.next;
}
System.out.println();
}
}