Reverse a singly linked list.java
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
复制代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val; // 数据域
* ListNode *next; //指针域
* ListNode(int x) : val(x), next(NULL) {} //构造函数
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *new_head = NULL; //指向新链表头结点的指针
while (head){
ListNode *next = head->next;// 备份head->next
head->next = new_head;//更新head->next
new_head = head;// 移动new_head
head=next; // 遍历链表
}
return new_head;
}
};
复制代码
在遍历列表时,将当前节点的 next 指针改成指向前一个元素。因为节点没有引用其上一个节点,所以必须事先存储其前一个元素。在更改引用以前,还须要另外一个指针来存储下一个节点。不要忘记在最后返回新的头引用!bash
/**
* 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 prev =null;
ListNode curr =head;
while (curr!=null){
ListNode nextTemp = curr.next;
curr.next = prev;
prev=curr;
curr=nextTemp; // 遍历链表
}
return prev;
}
}
复制代码