Reverse a singly linked list.
逆置单链表。
Hint:
提示:
A linked list can be reversed either iteratively or recursively. Could you implement both?
单链表可以通过迭代或者递归来实现,你能都实现他们吗?
先用迭代的方式实现:从第二个节点开始,按顺序一个个将节点逆置。
需要用到三个指针:prev,current,pnext,分别指向逆置链表的最后一个节点、当前待逆置节点和下一个待逆置节点,一次逆置过程的操作如下:
具体步骤如下:
1、先将当前待操作节点的下一个节点地址保存:pnext=current->next;
2、将当前节点的next指针指向前一个已经逆置的节点prev:prev=current->next;
3、移动prev的位置,使其指向刚刚完成逆置的节点:prev=current;
4、移动current的位置,使其指向步骤1中保存的下一个节点地址:current=pnext;
我的完整实现如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *prev,*current,*pnext;
if(head)
{
prev=head;
current=prev->next;
while(current)
{
pnext=current->next;
current->next=prev;
prev=current;
current=pnext;
}
head->next=NULL;
return prev;
}
else
return NULL;
}
这种方法并不完美,多了一层判断,查了Editorial 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;
}
原理是一样的,但这里给prev赋了初值NULL,给curr头指针head,如果头指针为空,则直接return prev,若非空,进入while循环后会将NULL当作一个节点使得头结点指向它,这样一来不需要再head->next=NULL。
关于递归的实现,可以看这里 https://leetcode.com/articles/reverse-linked-list/