当前位置:网站首页>Question brushing record ---- reverse the linked list (reverse the whole linked list)
Question brushing record ---- reverse the linked list (reverse the whole linked list)
2022-07-28 06:46:00 【HandsomeDog_ L】
Catalog
Title Description : Given a linked list , Invert and return to the new header node
recursive : Reverse from back to front
hold head.next Later nodes are treated as a node
Title Description : Given a linked list , Invert and return to the new header node
iteration :
Two pointers ,pre and cur,cur Traverse the linked list instead of the head node , In the process next Record cur.next
ListNode reverse(ListNode head) {
ListNode pre = null, cur = head;
while (cur != null) {
ListNode next = cur.next;// Record the next node
cur.next = pre;// Change the direction of the first node
pre = cur;// The predecessor node is updated to the current node
cur = next;// Update node backward
}
return pre;
}recursive :
public ListNode reverseList(ListNode head) {
return reverse(null, head);
}
private ListNode reverse(ListNode prev, ListNode cur) {
if (cur == null) {
return prev;
}
ListNode temp = null;
temp = cur.next;// Save the next node first
cur.next = prev;// reverse
// to update prev、cur Location
// prev = cur;
// cur = temp;
return reverse(cur, temp);
}recursive : Reverse from back to front
hold head.next Later nodes are treated as a node
ListNode reverseList(ListNode head) {
// Edge condition judgment
if(head == null) return null;
if (head.next == null) return head;
// Recursively call , Flip the second node and start the subsequent linked list
ListNode last = reverseList(head.next);
// Turn the direction between the head node and the second node
head.next.next = head;
// At this time head The node is the tail node ,next Need to point to NULL
head.next = null;
return last;
} 边栏推荐
猜你喜欢
随机推荐
网络通信及TCP/IP协议
[PTA----输出全排列]
Ready to start blogging
战疫杯--奇奇怪怪的形状
OJ 1284 记数问题
【详解如何一步步实现三子棋】
【无标题】
Feignclient @requestmapping parameter setting and simple method setting of request header
SSAO by computer shader (II)
江中ACM新生10月26日习题题解
OJ 1242 大一上之初出茅庐
Mongodb quick start
2022-05-24 use of spiel
费马小定理
Development of Quantitative Trading Robot System
水渲染示例
NIO示例
SSAO By Computer Shader(二)
Execjs call
NFT data storage blind box + mode system development





![[untitled]](/img/54/660667e528729cc87796d972dc0b17.png)


![[pta---- output full arrangement]](/img/66/d1699cd55fa5ff4a55e3e150d02c1b.png)
