题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路
第一次循环
第二次循环
第三次循环
Java 代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode phead = new ListNode(-1);
ListNode tmp = null;
while(head != null){
tmp = phead.next;
phead.next = head;
head = head.next;
phead.next.next = tmp;
}
return phead.next;
}
}
python 代码
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
head = ListNode(-1)
while pHead is not None:
tmp = head.next
head.next = pHead
pHead = pHead.next
head.next.next = tmp
return head.next
if __name__ == '__main__':
l=LinkList()
data1 = [1, 2, 3]
l1=l.initList(data1)
l.printlist(l1)
# ###################################
s = Solution()
res = s.ReverseList(l1)
print(res)