题目:
输入一个链表,反转链表后,输出新链表的表头。
思路:
利用头插法,或者利用栈
Java
利用头插法:
package nowcoder;
public class S15_ReverseList {
public ListNode reverseList(ListNode head){
//利用头插法
ListNode pre = head;
ListNode p, q;
if (head == null)
return null;
p = pre.next;
while (p !=null){
q = p.next;
pre.next = null;
p.next = pre;
pre = p;
p = q;
}
return p;
}
public static void main(String[] args){
S15_ReverseList s15 = new S15_ReverseList();
S14_FindKthToTail s14 = new S14_FindKthToTail();
int[] array = {1,2,3,4,5,6,7,8,10};
ListNode head = s14.arrayToList(array, 0);
ListNode result = s15.reverseList(head);
if (result == null)
System.out.print("null");
else
System.out.print(result.val);
}
}
利用栈
package nowcoder;
import java.util.Stack;
public class S15_ReverseList {
public ListNode reverseList(ListNode head){
//利用栈
Stack<ListNode> stack = new Stack<ListNode>();
ListNode p = head;
//最后一个节点不进栈
while (p.next != null){
stack.push(p);
p = p.next;
}
ListNode q = p; //最后一个节点
while (!stack.isEmpty()){
q.next = stack.pop();
q = q.next;
}
return p;
}
public static void main(String[] args){
S15_ReverseList s15 = new S15_ReverseList();
S14_FindKthToTail s14 = new S14_FindKthToTail();
int[] array = {1,2,3,4,5,6,7,8,10};
ListNode head = s14.arrayToList(array, 0);
ListNode result = s15.reverseList(head);
if (result == null)
System.out.print("null");
else
System.out.print(result.val);
}
}
Python
from S14_FindKthToTail14 import FindKthToTail
class ReverseList:
def reverseList(self, pHead):
if not pHead or not pHead.next:
return pHead
p = pHead.next
pHead.next = None
while p:
p1 = p.next
p.next = pHead
pHead = p
p = p1
return pHead
if __name__ == '__main__':
test = ReverseList()
test14 = FindKthToTail()
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
head = test14.arrayToList(array, 0)
print(test.reverseList(head).val)