题目:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
思路:定义三个参数,pre、node和next,先把node的next设置为pre,然后再往后依次操作。当node的next为null时,返回node。
解决方案:
public class Question24 {
static class ListNode{
int value;
ListNode next;
public ListNode(int value){
this.value = value;
}
}
public static ListNode reverseList(ListNode head){
ListNode reverseHead = null;
ListNode node = head;
ListNode pre = null;
while (node != null){
ListNode next = node.next;
if (next == null){
reverseHead = node;
}
node.next = pre;
pre = node;
node = next;
}
return reverseHead;
}
public static void main(String[] args) {
ListNode pHead = new ListNode(1);
ListNode pAhead = new ListNode(3);
ListNode pBhead = new ListNode(5);
ListNode pChead = new ListNode(7);
pHead.next = pAhead;
pAhead.next = pBhead;
pBhead.next = pChead;
System.out.println(reverseList(pHead).value);
}
}
网友评论