题目:反转链表
分析:拿到这种题,一般先要知道链表这种结构,然后知道怎样遍历链表,这题比较简单,题眼在反转上,那么我第一个想到用栈这种数据结构来存储
思路:依次遍历链表将元素存入栈中,然后出栈,就得到相应的链表反转后的数据了
C++代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL||pHead->next==NULL){
return pHead;
}
stack<ListNode *> s;
ListNode *node = pHead;
ListNode *list;
while(node->next!=NULL){
s.push(node);
node = node->next;
}
list = node;
while(!s.empty()){
node->next = s.top();
node = node->next;
s.pop();
}
node->next = NULL;
return list;
}
};
Java代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null || head.next==null){
return head;
}
Stack<ListNode> s = new Stack<ListNode>();
ListNode p = head;
ListNode l;
while(p.next!=null){
s.push(p);
p = p.next;
}
l=p;
while(!s.empty()){
p.next=s.peek();
p=p.next;
s.pop();
}
p.next=null;
return l;
}
}