原题
Reverse a singly linked list.
题目分析
- 保存节点b后的所有节点顺序
- 上步保存后,可以放心的将b的next域指向a,实现反转
- 上步实现反转后,再赋值给a,这样a始终为反转链表的头节点
- 上步后实现了反转,这步实现迭代,即让b再在原来的链表中保持前行。
实现代码
public ListNode ReverseList(ListNode head)
{
if (head == null || head.next == null)
return head;
ListNode a = head;
ListNode b = head.next;
a.next = null;
while (b != null)
{
ListNode tmp = b.next; //保存节点b后的所有节点顺序
b.next = a; //上步保存后,可以放心的将b的next域指向a,实现反转
a = b; //上步实现反转后,再赋值给a,这样a始终为反转链表的头节点
b = tmp;//上步后实现了反转,这步实现迭代,即让b再在原来的链表中保持前行。
}
return a;
}
LinkedList的更多题目
http://blog.csdn.net/daigualu/article/details/69077428
随着学习的深入,对反转链表有了更深层次的认识,现记录到这里:
C语言版本:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <stdlib.h>
#include <stdio.h>
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL) return NULL;
struct ListNode *rev_head = head; /*reversed-listnode head*/
struct ListNode *cur_head = head->next; /*original listnode head*/
rev_head->next = NULL;
while(cur_head!=NULL) {
struct ListNode *next = cur_head->next; /*save next for original listnode head*/
cur_head->next = rev_head; /*current head points to reversed-list head*/
rev_head = cur_head; /*reversed-list head points to current head*/
cur_head = next; /*current head points to saved next node*/
}
return rev_head; /*return rev_head that consistently points to reversed-list head*/
}
以下是一个错误版本:仅有两行代码的顺序反了,
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <stdlib.h>
#include <stdio.h>
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL) return NULL;
struct ListNode *rev_head = head; /*reversed-listnode head*/
rev_head->next = NULL;
struct ListNode *cur_head = head->next; /*original listnode head*/
while(cur_head!=NULL) {
struct ListNode *next = cur_head->next; /*save next for original listnode head*/
cur_head->next = rev_head; /*current head points to reversed-list head*/
rev_head = cur_head; /*reversed-list head points to current head*/
cur_head = next; /*current head points to saved next node*/
}
return rev_head; /*return rev_head that consistently points to reversed-list head*/
}