算法练习(四):反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
解题思路:

考虑遍历链表,并在访问各节点时修改 next 引用指向package Algriothm;
public class Solution2 {
public static void main(String[] args) {
ListNode head1 = new ListNode(1);
ListNode head2 = new ListNode(2);
ListNode head3 = new ListNode(3);
ListNode head4 = new ListNode(4);
ListNode head5 = new ListNode(5);
head1.next = head2;
head2.next = head3;
head3.next = head4;
head4.next = head5;
System.out.println(reverseList(head1));
}
public static ListNode reverseList(ListNode head) {
// 赋值当前节点
ListNode cur = head, pre = null;
while (cur != null) {
// 第一次循环 tmp = 2-3-4-5-null cur.next = null pre = 1-null cur = 2-3-4-5-null
// 第二次循环 tmp = 3-4-5-null cur.next = 1-null pre = 2-1-null cur = 3-4-5-null
// 第三次循环 tmp = 4-5-null cur.next = 2-1-null pre = 3-2-1-null cur = 4-5-null
....
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
浙公网安备 33010602011771号