您的位置:首页 > Web前端

《剑指offer》——反转链表

2015-11-01 21:12 302 查看
T:

题目描述

输入一个链表,反转链表后,输出链表的所有元素。

constraints:

时间限制:1秒空间限制:32768K

考察的是对链表的操作。

跟排序差不多,依次讲节点插入头部,“头插法”。



code:

/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {

ListNode tempHead = new ListNode(0);
tempHead.next = head;
ListNode node = null;

// 空链表的情况
if (head == null) {
return head;
}

while (head.next != null) {
node = head.next;   // 将要插入前面的节点存储;
head.next = head.next.next; // 指针转换到其后继节点;
node.next = tempHead.next;  // 将该节点的指针指向第一个节点;
tempHead.next = node;   // 将虚的头结点的指针指向该节点。
}

return tempHead.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: