题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
C++代码如下:
方法一:(不太符合题意)
/**
* 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) {
if(head==NULL)
{
return NULL;
}
else
{
ListNode*p=head;
stack<int>s;//反转问题都考虑一下栈
while(p!=NULL){
s.push(p->val);
p=p->next;
}
ListNode*q=new ListNode;
ListNode*r=q;
r->next=NULL;
q->val=s.top();
s.pop();
while(!s.empty()){
ListNode*pNew=new ListNode;
pNew->val = s.top();
r->next = pNew;
pNew->next = NULL;
r = pNew;
s.pop();
}
return q;
}
}
};
方法二:
双指针
1 定义两个指针: pre 和 cur ;pre 在前 curr在后
2 每次让 pre 的 next指向cur ,实现一次局部反转
3 局部反转完成之后, pre和 cur 同时往前移动一个位置
4 循环上述过程,直至 pre 到达链表尾部
代码如下:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = NULL, *pre = head;
while (pre != NULL) {
ListNode* t = pre->next;
pre->next = cur;
cur = pre;
pre = t;
}
return cur;
}
};
JAVA代码如下:
方法一:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return head;
}
ListNode h=new ListNode();
ListNode q=h;
q.next=null;
ListNode node =head;
Stack<Integer> s=new Stack<>();
while(node!=null){
s.push(node.val);
node=node.next;
}
h.val=s.pop();
int n=s.size();
for(int i=0;i<n;i++){
ListNode p=new ListNode();
p.val=s.pop();
q.next=p;
q=p;
}
return h;
}
}
方法二:(递归写法)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode last=reverseList(head.next);
head.next.next=head;
head.next=null;
return last;
}
}
方法三:(迭代,双指针)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return head;
}
ListNode slow=null;
ListNode fast=head;
while(fast!=null){
ListNode t=fast.next;
fast.next=slow;
slow=fast;
fast=t;
}
return slow;
}
}