206.反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
递归
以上例说明,2->3->4->5->NULL是一个子问题,将这个子链反转后再将首节点接到子链的尾部,子链的首部作为反转后链表的首部。
ListNode* reverseList(ListNode* head) {
if(!head||!head->next) return head;
ListNode*rest=reverseList(head->next);
ListNode*last=rest;
while(last->next) last=last->next;
last->next=head;
head->next=NULL;
return rest;
}
迭代一
思路:从第二个结点开始,依次向前插入。
需要用到三个指针:首节点head(已知,不用自己定义),插入节点的前一个节点pre(用于指向插入节点之后的节点),插入节点cur(插入到head之前)。
ListNode* reverseList(ListNode* head) {
if(!head||!head->next) return head;
ListNode*pre=head,*cur=head->next;
while(cur){
pre->next=cur->next;
cur->next=head;
head=cur;
cur=pre->next;
}
return head;
}
迭代二
思路:上一种方法是每次向前插入一个节点都会生成新的链表,而这一种方法则没有;这一种方法是将链表分为两部分,第一部分起始只有head节点(head->next=NULL,将链表分割为两部分),第二部分为剩余节点。遍历第二部分将节点插入第一部分head节点之前。
需要用到三个指针:第一部分的头节点head(已知,不用自己定义),插入节点cur,插入节点后面的节点next(记录下一个插入节点,因为两部分是分离的,如果不记录就找不到下一次要插入的节点)。
ListNode* reverseList(ListNode* head) {
if(!head||!head->next) return head;
ListNode*cur=head->next,*next=cur->next;
head->next=NULL;
while(cur){
next=cur->next;
cur->next=head;
head=cur;
cur=next;
}
return head;
}
类似题目:92.反转链表II