链表倒置(C++&JAVA)
调整指针倒置链表(C++实现):
解题思路:
通过将所有结点的指针方向逆置来形成整个链表的逆置。
p1、p2和p3指针分别对应前中后三个位置的结点,其中p1初始为空,p2为头指针。
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL)return NULL;
ListNode *p1=NULL;
ListNode *p2=pHead;
ListNode *p3=p2->next;
while(p2!=NULL){
p2->next=p1;
p1=p2;
p2=p3;
p3=p3->next;
}
return p1;
}
};
利用栈倒置链表(JAVA实现):
解题思路:
用栈先进后出的特性。
先将链表全部压入栈再弹出,就能得到新的逆置链表。
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null)return null;
Stack<ListNode> s=new Stack<>();
while(head!=null){//原链表全部压入栈
s.push(head);
head=head.next;
}
ListNode n=s.pop();
ListNode nx=n;//nx为逆置后链表的头节点
while(!s.isEmpty()){//这里有点繁琐,其实就是顺序出栈,再将元素链接成新的链表
ListNode nn=s.pop();
n.next=nn;
n=n.next;
}
n.next=null;
return nx;
}
}