- 1、题目描述:
-3、 设计思想:
详细操作流程看下图:
-4、视频讲解链接B站视频讲解
-5、代码:
c++版本:
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { ListNode *res = NULL; //定义新的链表 ListNode *cur = pHead;//用来遍历pHead指针 while(cur != NULL){ //用来翻转链表 ListNode *temp = cur->next; cur->next = res; res = cur; cur = temp; } return res; } };
Java版本:
public class Solution { public ListNode ReverseList(ListNode head) { ListNode res = null; ListNode cur = head; while(cur != null){ ListNode temp = cur.next; cur.next = res; res = cur; cur = temp; } return res; } }
Python版本:
class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here res = None#定义新的链表 cur = pHead#用来遍历pHead指针 while cur != None:#用来翻转链表 temp = cur.next cur.next = res res = cur cur = temp return res
JavaScript代码:
/*function ListNode(x){ this.val = x; this.next = null; }*/ function ReverseList(pHead) { // write code here let res = null;//定义新的链表 let cur = pHead;//用来遍历pHead指针 while(cur != null){ ///进行当前节点的翻转 let temp = cur.next; cur.next = res; res = cur; cur = temp; } return res; } module.exports = { ReverseList : ReverseList };