<剑指offer> 第13题

题目:

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点

思路:

(1)保存当前节点的下一个节点

(2)将当前节点的next指向反转,指向上一个节点

(3)更新pre为当前节点

(4)将当前节点改为下一个节点

代码实现:

public class Thirdteenth {
class ListNode{
ListNode next;
int val;
}
public static ListNode reverseList(ListNode head){
if (head == null){
return null;
}
ListNode cur = head;
ListNode pre = null;
while(cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}

猜你喜欢

转载自www.cnblogs.com/HarSong13/p/11327550.html